import Layout from '@/components/Layout';
import React, { useEffect, useRef, useState } from 'react';
import {
    Table,
    TableBody,
    TableCell,
    TableFooter,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import {
    EllipsisVertical,
    FolderClosed,
    Plus,
    SearchIcon,
    X,
} from 'lucide-react';
import {
    Empty,
    EmptyDescription,
    EmptyHeader,
    EmptyMedia,
    EmptyTitle,
} from '@/components/ui/empty';
import {
    InputGroup,
    InputGroupAddon,
    InputGroupInput,
} from '@/components/ui/input-group';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { router, useForm } from '@inertiajs/react';
import { Field, FieldDescription, FieldLabel } from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import AppPagination from '@/components/AppPagination';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import PageHeader from '@/components/PageHeader';
import {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxList,
} from '@/components/ui/combobox';

interface BankData {
    id: number;
    label: string;
    bank_name: string;
    balance?: number | 0;
}
interface TableData {
    id: any;
    uid: string;
    note: string;
    amount: number;
    date: string;
    bank_id: number;
    bank?: {
        id: string;
        label: string;
        bank_name?: string;
    };
    manager?: {
        name: string;
        email: string;
    };
}
interface FilterData {
    search?: string;
    start_at?: string;
    end_at?: string;
}
interface LinkData {
    url: string | null;
    label: string;
    active: boolean;
}
interface PageProps {
    data: {
        data: TableData[];
        current_page: number;
        last_page: number;
        links: LinkData[];
        from: number | null;
        to: number | null;
        total: number;
    };
    filter?: FilterData;
    tab?: string;
    bank?: BankData[];
}

interface FormData {
    id: number | '';
    amount: number | 0;
    note: string | '';
    bank_id?: number | null;
    date: string;
}

export default function expense({
    data: initData,
    filter,
    tab,
    bank,
}: PageProps) {
    const [formDialog, setFormDialog] = useState(false);
    useEffect(() => {
        if (tab == 'open') {
            setFormDialog(true);
        }
    }, [tab]);

    // form
    const { data, setData, processing, post, reset, errors } =
        useForm<FormData>({
            id: '',
            note: '',
            amount: 0,
            date: new Date().toISOString().split('T')[0],
            bank_id: null,
        });
    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        post(route('expense.store'), {
            preserveScroll: true,
            onSuccess: () => {
                reset();
                setFormDialog(false);
            },
        });
    };

    // total
    const total = initData?.data?.reduce(
        (sum, item) => sum + Number(item.amount),
        0,
    );

    // search
    const [search, setSearch] = useState(filter?.search || '');
    const [searchStartAt, setSearchStartAt] = useState(filter?.start_at || '');
    const [searchEndAt, setSearchEndAt] = useState(filter?.end_at || '');
    const isFirstRender = useRef(true);
    useEffect(() => {
        if (isFirstRender.current) {
            isFirstRender.current = false;
            return;
        }
        const delayDebounceFn = setTimeout(() => {
            router.get(
                route('expense.index'),
                {
                    search: search,
                    start_at: searchStartAt,
                    end_at: searchEndAt,
                },
                {
                    preserveState: true,
                    replace: true,
                },
            );
        }, 500);
        return () => clearTimeout(delayDebounceFn);
    }, [search, searchStartAt, searchEndAt]);

    // warning
    const [amountWarning, setAmountWarning] = useState(false);
    useEffect(() => {
        if (!data.bank_id || Number(data.amount) <= 0) {
            setAmountWarning(false);
            return;
        }

        const currentBank = bank?.find((b) => b.id === Number(data.bank_id));

        setAmountWarning(
            Number(currentBank?.balance ?? 0) < Number(data.amount),
        );
    }, [data.bank_id, data.amount, bank]);
    return (
        <Layout title="Expense">
            <PageHeader
                title="All Expenses"
                subtitle="Track and manage all your business expenses."
            >
                <div className="flex flex-col items-center gap-2 md:flex-row">
                    <InputGroup className="w-full md:w-fit">
                        <InputGroupInput
                            id="inline-start-input"
                            type="search"
                            placeholder="Search..."
                            onChange={(e) => setSearch(e.target.value)}
                            value={search}
                        />
                        <InputGroupAddon align="inline-start">
                            <SearchIcon className="text-muted-foreground" />
                        </InputGroupAddon>
                    </InputGroup>
                    <div className="grid grid-cols-2 gap-2">
                        <Input
                            type="date"
                            value={searchStartAt}
                            onChange={(e) => setSearchStartAt(e.target.value)}
                        />
                        <Input
                            type="date"
                            value={searchEndAt}
                            onChange={(e) => setSearchEndAt(e.target.value)}
                        />
                    </div>
                    <Button onClick={() => setFormDialog(true)}>
                        <Plus className="size-4" />
                        Add Expense
                    </Button>
                    {(search || searchStartAt || searchEndAt) && (
                        <Button
                            onClick={() => router.get(route('expense.index'))}
                            variant="destructive"
                            size="icon"
                        >
                            <X />
                        </Button>
                    )}
                </div>
            </PageHeader>

            <Card>
                <CardContent>
                    {initData?.data?.length > 0 ? (
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead className="w-25">ID</TableHead>
                                    <TableHead>Date</TableHead>
                                    <TableHead>Bank</TableHead>
                                    <TableHead>BY</TableHead>
                                    <TableHead>Note</TableHead>
                                    <TableHead className="text-right">
                                        Amount
                                    </TableHead>
                                    <TableHead className="text-right"></TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {initData?.data?.map((items) => (
                                    <TableRow key={items.id}>
                                        <TableCell className="font-medium">
                                            {items.uid}
                                        </TableCell>
                                        <TableCell>{items.date}</TableCell>
                                        <TableCell>
                                            <p className="font-bold">
                                                {items.bank?.label}
                                            </p>
                                            <p className="text-xs">
                                                {items.bank?.bank_name}
                                            </p>
                                        </TableCell>
                                        <TableCell>
                                            <p className="font-bold">
                                                {items.manager?.name}
                                            </p>
                                            <p className="text-xs">
                                                {items.manager?.email}
                                            </p>
                                        </TableCell>
                                        <TableCell>{items.note}</TableCell>
                                        <TableCell className="text-right">
                                            {items.amount.toLocaleString(
                                                'en-BD',
                                                {
                                                    minimumFractionDigits: 1,
                                                    maximumFractionDigits: 1,
                                                },
                                            )}
                                        </TableCell>
                                        <TableCell className="text-right">
                                            <DropdownMenu>
                                                <DropdownMenuTrigger
                                                    render={
                                                        <Button
                                                            variant="ghost"
                                                            size="icon"
                                                            className="size-8"
                                                        >
                                                            <EllipsisVertical />
                                                            <span className="sr-only">
                                                                Open menu
                                                            </span>
                                                        </Button>
                                                    }
                                                />
                                                <DropdownMenuContent align="end">
                                                    <DropdownMenuItem
                                                        variant="destructive"
                                                        onClick={() => {
                                                            router.get(
                                                                route(
                                                                    'expense.delete',
                                                                    {
                                                                        id: items.id,
                                                                    },
                                                                ),
                                                            );
                                                        }}
                                                    >
                                                        Delete
                                                    </DropdownMenuItem>
                                                </DropdownMenuContent>
                                            </DropdownMenu>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                            <TableFooter>
                                <TableRow>
                                    <TableCell colSpan={5}>Total</TableCell>
                                    <TableCell className="text-right">
                                        {total?.toLocaleString('en-BD', {
                                            minimumFractionDigits: 1,
                                            maximumFractionDigits: 1,
                                        })}
                                    </TableCell>
                                    <TableCell></TableCell>
                                </TableRow>
                                <AppPagination data={initData} />
                            </TableFooter>
                        </Table>
                    ) : (
                        <Empty>
                            <EmptyHeader>
                                <EmptyMedia variant="icon">
                                    <FolderClosed />
                                </EmptyMedia>
                                <EmptyTitle>No Expense Yet</EmptyTitle>
                                <EmptyDescription>
                                    You haven't created any expense yet. Get
                                    started by creating your first expense.
                                </EmptyDescription>
                            </EmptyHeader>
                        </Empty>
                    )}
                </CardContent>

                <AppPagination data={initData} />
            </Card>

            {/* add and update dialog */}
            <Dialog open={formDialog}>
                <DialogContent showCloseButton={false} className="md:w-120">
                    <DialogHeader className="border-b border-border pb-2">
                        <DialogTitle>Add New Expense</DialogTitle>
                        <DialogDescription>
                            Record your expense details to keep your business
                            finances organized.
                        </DialogDescription>
                    </DialogHeader>

                    <div className="w-full space-y-5">
                        <Field>
                            <FieldLabel htmlFor="checkout-7j9-card-name-43j">
                                Bank*
                            </FieldLabel>
                            <Combobox
                                items={bank}
                                onValueChange={(value) =>
                                    setData('bank_id', Number(value) || null)
                                }
                            >
                                <ComboboxInput
                                    value={
                                        bank?.find((p) => p.id == data.bank_id)
                                            ?.label ?? ''
                                    }
                                    placeholder="Select a company"
                                    showClear
                                />
                                <ComboboxContent>
                                    <ComboboxEmpty>
                                        No items found.
                                    </ComboboxEmpty>
                                    <ComboboxList>
                                        {(item) => (
                                            <ComboboxItem
                                                key={item.id}
                                                value={item.id}
                                            >
                                                {item.label} - {item.balance}
                                            </ComboboxItem>
                                        )}
                                    </ComboboxList>
                                </ComboboxContent>
                            </Combobox>
                            {errors.bank_id && (
                                <FieldDescription className="text-destructive">
                                    {errors.bank_id}
                                </FieldDescription>
                            )}
                        </Field>
                        <Field>
                            <FieldLabel>Amount*</FieldLabel>
                            <Input
                                type="number"
                                value={data.amount}
                                onChange={(e) =>
                                    setData(
                                        'amount',
                                        Number(e.target.value || 0),
                                    )
                                }
                            />
                            {amountWarning && (
                                <FieldDescription className="text-destructive">
                                    Insufficient bank balance. Available
                                    balance: ৳
                                    {Number(
                                        bank?.find(
                                            (b) =>
                                                b.id === Number(data.bank_id),
                                        )?.balance ?? 0,
                                    ).toLocaleString('en-BD', {
                                        minimumFractionDigits: 2,
                                    })}
                                </FieldDescription>
                            )}
                            {errors.amount && (
                                <FieldDescription className="text-destructive">
                                    {errors.amount}
                                </FieldDescription>
                            )}
                        </Field>
                        <Field>
                            <FieldLabel>Date*</FieldLabel>
                            <Input
                                type="date"
                                value={data.date}
                                onChange={(e) =>
                                    setData('date', e.target.value)
                                }
                            />
                            {errors.date && (
                                <FieldDescription className="text-destructive">
                                    {errors.date}
                                </FieldDescription>
                            )}
                        </Field>
                        <Field>
                            <FieldLabel>Note*</FieldLabel>
                            <Textarea
                                value={data.note}
                                onChange={(e) =>
                                    setData('note', e.target.value)
                                }
                            />
                            {errors.note && (
                                <FieldDescription className="text-destructive">
                                    {errors.note}
                                </FieldDescription>
                            )}
                        </Field>
                    </div>

                    <DialogFooter className="flex items-center justify-end gap-2">
                        <Button
                            onClick={() => {
                                if (tab == 'open') {
                                    router.get(route('expense.index'));
                                }
                                reset();
                                setFormDialog(false);
                            }}
                            size="sm"
                            variant="outline"
                        >
                            Close
                        </Button>
                        <Button
                            onClick={handleSubmit}
                            size="sm"
                            variant="default"
                            disabled={processing}
                        >
                            Save Now{processing && '...'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </Layout>
    );
}
