import AddItemForm from '@/components/jbs/add-item-form';
import AddSection from '@/components/jbs/add-section';
import InputJbs from '@/components/jbs/input';
import ShowHtml from '@/components/jbs/show-html';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Box, Card, CardContent, Divider, Grid, Paper, Typography } from '@mui/material';
import Backdrop from '@mui/material/Backdrop';
import CircularProgress from '@mui/material/CircularProgress';
import axios from 'axios';
import { useEffect, useRef, useState } from 'react';

export default function InvoiceItemList(props) {
    const { invoice_id } = props;

    const breadcrumbs: BreadcrumbItem[] = [
        {
            title: 'Invoices',
            href: '/invoices',
        },
        {
            title: 'Invoice Items',
            href: '#',
        },
    ];

    const [invoiceData, setInvoiceData] = useState({});
    const [addItemVisibility, setAddItemVisibility] = useState({}); // Track visibility for each section

    const getinvoiceData = async () => {
        if (invoice_id) {
            const { data: invoiceData } = await axios.get(route('invoices.show', { invoice: invoice_id, with: 'items' }));
            if (invoiceData.success) {
                setOverlay(false);
                setInvoiceData(invoiceData.data);
            }
        }
    };

    const addItem = async (item) => {
        item['invoice_id'] = invoice_id;

        const { data } = await axios.post(route('invoices.items.store', { invoice: invoice_id }), {
            ...item,
        });

        if (data.success) {
            getinvoiceData();
            // Hide the add item form after successful addition
            setAddItemVisibility((prev) => ({ ...prev, [item.section_id]: false }));
        }
    };

    const deleteItem = async (item_id) => {
        const confirmDelete = confirm('are you sure you want to delete this item');
        if (confirmDelete) {
            const { data } = await axios.delete(route('invoices.items.destroy', { invoice: invoice_id, item: item_id }));
            if (data.success) {
                getinvoiceData();
            }
        }
    };

    const debounceTimer = useRef(null);
    const handleNoteChange = (event) => {
        const value = event.target.value;
        setInvoiceData({ ...invoiceData, notes: value });

        // Clear previous timer
        if (debounceTimer.current) {
            clearTimeout(debounceTimer.current);
        }

        debounceTimer.current = setTimeout(() => {
            axios.post(route('invoices.update.notes', { invoice: invoice_id }), { notes: value });
        }, 800);
    };

    const moveItemToIndex = (array, fromIndex, toIndex) => {
        const newArray = [...array];
        const item = newArray[fromIndex];
        newArray.splice(fromIndex, 1);
        newArray.splice(toIndex, 0, item);
        return newArray;
    };

    const onDragEnd = async (result) => {
        if (!result.destination) {
            return;
        }
        if (result.destination.index === result.source.index) {
            return;
        }
        const items = moveItemToIndex(invoiceData.items, result.source.index, result.destination.index);
        const updatedItems = items.map((item, index) => ({ ...item, sort_order: index + 1 }));
        setInvoiceData({ ...invoiceData, items: updatedItems });

        // try {
        const itemsWithOrder = updatedItems.map((item) => ({
            id: item.id,
            sort_order: item.sort_order,
        }));
        await axios.post(route('invoices.items.reorder', { invoice: invoice_id }), {
            items: itemsWithOrder,
        });
        // } catch (error) {
        //     getinvoiceData();
        // }
    };

    const [overlay, setOverlay] = useState(false);

    const createSection = async (sectionData) => {
        sectionData['invoice_id'] = invoice_id;
        const { data } = await axios.post(route('invoices.sections.store', { invoice: invoice_id }), sectionData);
        if (data.success) {
            getinvoiceData();
        }
    };

    const toggleAddItemVisibility = (sectionId) => {
        setAddItemVisibility((prev) => ({
            ...prev,
            [sectionId]: !prev[sectionId],
        }));
    };

    useEffect(() => {
        setOverlay(true);
        getinvoiceData();
    }, [invoice_id]);

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Paper elevation={3} sx={{ p: 4 }} style={{ backgroundColor: 'rgb(253 244 235 / 28%)' }}>
                {/* Header */}

                <Backdrop open={overlay} style={{ zIndex: 111111, color: '#fff' }}>
                    <CircularProgress color="inherit" />
                </Backdrop>

                <Grid container spacing={2}>
                    <Grid size={8}>
                        <Typography variant="h4" sx={{ fontWeight: 'bold' }}>
                            {invoiceData.business_name}
                        </Typography>
                        <b>{invoiceData.user_name}</b><br/>
                        <b>Phone:</b> <a href="tel:{{ $user_mobile }}">{invoiceData.user_mobile }</a><br/>
                        <b>Email:</b> <a href="mailto:{{ $user_email }}">{ invoiceData.user_email }</a><br/>
                    </Grid>
                    <Grid size={4} textAlign="right" >
                        <Typography variant="h4" sx={{ fontWeight: 'bold' }}>Invoice</Typography>
                        <b>Invoice:</b> {invoiceData.invoice_number_display}<br/>
                    </Grid>
                </Grid>

                <Divider sx={{ my: 3 }} />

                {/* Invoice To & Bill To */}
                <Grid container spacing={2}>
                    <Grid size={6}>
                        <Typography fontWeight="bold">To:</Typography>
                        <Typography style={{ marginTop: '20px', fontWeight: 'bold' }}>{invoiceData.customer_name}</Typography>
                        <ShowHtml content={invoiceData.customer_address} />
                    </Grid>
                    {invoiceData.interior_designer_id && (
                        <Grid size={6}>
                            <Typography fontWeight="bold">Interior Designer:</Typography>
                            <Typography style={{ marginTop: '20px', fontWeight: 'bold' }}>{invoiceData.interior_designer_name}</Typography>
                            {invoiceData.interior_designer_mobile && (
                                <Typography>
                                    <a href={`tel:${invoiceData.interior_designer_mobile}`}>{invoiceData.interior_designer_mobile}</a>
                                </Typography>
                            )}
                            {invoiceData.interior_designer_email && (
                                <Typography>
                                    <a href={`mailto:${invoiceData.interior_designer_email}`}>{invoiceData.interior_designer_email}</a>
                                </Typography>
                            )}
                        </Grid>
                    )}
                </Grid>

                <Divider sx={{ my: 3 }} />

                {invoiceData.sections &&
                    invoiceData.sections.map((section, index) => (
                        <Card
                            key={section.id || index}
                            style={{ marginTop: '20px', borderLeft: '4px solid rgb(229 168 107)', borderRadius: '10px 0px 0px 10px' }}
                        >
                            <CardContent style={{ backgroundColor: '#fffdf7' }}>
                                <Typography gutterBottom variant="h5" component="div">
                                    {section.title}
                                </Typography>
                                <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                                    {section.items && section.items.length > 0 ? (
                                        section.items.map((item) => (
                                            <div style={{ marginBottom: '10px' }}>
                                                <AddItemForm
                                                    key={item.id}
                                                    onItemAdd={addItem}
                                                    onItemDelete={deleteItem}
                                                    item={item}
                                                    onlyDisplay={true}
                                                />
                                            </div>
                                        ))
                                    ) : (
                                        <div>No items Added</div>
                                    )}
                                    <br />
                                    <a
                                        onClick={() => toggleAddItemVisibility(section.id)}
                                        href="javascript:void(0)"
                                        style={{ cursor: 'pointer', textDecoration: 'underline' }}
                                    >
                                        {addItemVisibility[section.id] ? 'Cancel' : 'Add Item'}
                                    </a>
                                    {addItemVisibility[section.id] && (
                                        <div style={{ marginTop: '10px' }}>
                                            <AddItemForm
                                                onItemAdd={(form) => addItem({ ...form, invoice_section_id: section.id })}
                                                section_id={section.id}
                                            />
                                        </div>
                                    )}
                                </Typography>
                            </CardContent>
                        </Card>
                    ))}

                <Grid container style={{ marginTop: '20px' }}>
                    <Grid size={12}>
                        <AddSection onCreate={createSection} />
                    </Grid>
                </Grid>

                {/* <AddItemForm key="new" onItemAdd={addItem} /> */}

                {/* Item Entry */}

                <Divider sx={{ my: 3 }} />

                {/* Summary & Footer */}
                <Grid container spacing={2}>
                    <Grid size={12}>
                        <InputJbs
                            defaultValue={invoiceData.notes}
                            onChange={(e) => handleNoteChange(e)}
                            size="small"
                            label="Note"
                            fullWidth
                            multiline
                            rows={3}
                        />
                    </Grid>
                </Grid>
            </Paper>
        </AppLayout>
    );
}
