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 EstimateItemList(props) {
    const { estimate_id } = props;

    const breadcrumbs: BreadcrumbItem[] = [
        {
            title: 'Estimates',
            href: '/estimates',
        },
        {
            title: 'Estimate Items',
            href: '#',
        },
    ];

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

    const getEstimateData = async () => {
        if (estimate_id) {
            const { data: estimateData } = await axios.get(route('estimates.show', { estimate: estimate_id, with: 'items' }));
            if (estimateData.success) {
                setOverlay(false);
                setEstimateData(estimateData.data);
            }
        }
    };

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

        const { data } = await axios.post(route('estimates.items.store', { estimate: estimate_id }), {
            ...item,
        });

        if (data.success) {
            getEstimateData();
            // 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('estimates.items.destroy', { estimate: estimate_id, item: item_id }));
            if (data.success) {
                getEstimateData();
            }
        }
    };

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

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

        debounceTimer.current = setTimeout(() => {
            axios.post(route('estimates.update.notes', { estimate: estimate_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(estimateData.items, result.source.index, result.destination.index);
        const updatedItems = items.map((item, index) => ({ ...item, sort_order: index + 1 }));
        setEstimateData({ ...estimateData, items: updatedItems });

        // try {
        const itemsWithOrder = updatedItems.map((item) => ({
            id: item.id,
            sort_order: item.sort_order,
        }));
        await axios.post(route('estimates.items.reorder', { estimate: estimate_id }), {
            items: itemsWithOrder,
        });
        // } catch (error) {
        //     getEstimateData();
        // }
    };

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

    const createSection = async (sectionData) => {
        sectionData['estimate_id'] = estimate_id;
        const { data } = await axios.post(route('estimates.sections.store', { estimate: estimate_id }), sectionData);
        if (data.success) {
            getEstimateData();
        }
    };

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

    useEffect(() => {
        setOverlay(true);
        getEstimateData();
    }, [estimate_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' }}>
                            {estimateData.business_name}
                        </Typography>
                        <b>{estimateData.user_name}</b><br/>
                        <b>Phone:</b> <a href="tel:{{ $user_mobile }}">{estimateData.user_mobile }</a><br/>
                        <b>Email:</b> <a href="mailto:{{ $user_email }}">{ estimateData.user_email }</a><br/>
                    </Grid>
                    <Grid size={4} textAlign="right" >
                        <Typography variant="h4" sx={{ fontWeight: 'bold' }}>Estimate</Typography>
                        <b>Estimate:</b> {estimateData.estimate_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' }}>{estimateData.customer_name}</Typography>
                        <ShowHtml content={estimateData.customer_address} />
                    </Grid>
                    {estimateData.interior_designer_id && (
                        <Grid size={6}>
                            <Typography fontWeight="bold">Interior Designer:</Typography>
                            <Typography style={{ marginTop: '20px', fontWeight: 'bold' }}>{estimateData.interior_designer_name}</Typography>
                            {estimateData.interior_designer_mobile && (
                                <Typography>
                                    <a href={`tel:${estimateData.interior_designer_mobile}`}>{estimateData.interior_designer_mobile}</a>
                                </Typography>
                            )}
                            {estimateData.interior_designer_email && (
                                <Typography>
                                    <a href={`mailto:${estimateData.interior_designer_email}`}>{estimateData.interior_designer_email}</a>
                                </Typography>
                            )}
                        </Grid>
                    )}
                </Grid>

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

                {estimateData.sections &&
                    estimateData.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, estimate_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={estimateData.notes}
                            onChange={(e) => handleNoteChange(e)}
                            size="small"
                            label="Note"
                            fullWidth
                            multiline
                            rows={3}
                        />
                    </Grid>
                </Grid>
            </Paper>
        </AppLayout>
    );
}
