import { Head, Link, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { CardTable } from '@/components/data-display';
import { DeleteConfirmDialog } from '@/components/dialogs';
import { FilterPopover } from '@/components/data-display';
import { useCardTableExpand } from '@/components/hooks/use-card-table-expand';
import { PageHeader } from '@/components/layout';
import { Button } from '@/components/ui/button';
import {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxList,
} from '@/components/ui/combobox';
import { useCan } from '@/hooks/use-can';
import { useServerTable } from '@/hooks/use-server-table';
import {
    destroy,
    create as purchaseCreate,
    edit as purchaseEdit,
    index as purchaseIndex,
    items as purchaseItems,
} from '@/routes/admin/manage/purchases';
import type { Purchase, PurchaseItemDetail } from './columns';
import { PurchaseCardRow } from './purchase-card';
import { PurchaseItemSubRow } from './purchase-sub-row';

type Props = {
    purchases: {
        data: Purchase[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    suppliers: {
        id: number;
        name: string;
    }[];
    filters: {
        supplier_id?: string;
    };
    highlight?: number;
};

export default function PurchaseIndex({
    purchases,
    filters,
    suppliers,
    highlight,
}: Props) {
    const { can } = useCan();
    const [deleting, setDeleting] = useState<Purchase | null>(null);
    const [loadedItems, setLoadedItems] = useState<Record<number, PurchaseItemDetail[]>>({});
    const [loadingItems, setLoadingItems] = useState<Record<number, boolean>>({});
    const expand = useCardTableExpand(false);

    const pagination = {
        current_page: purchases.current_page,
        last_page: purchases.last_page,
        per_page: purchases.per_page,
        total: purchases.total,
    };

    const {
        search,
        filterOpen,
        setFilterOpen,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
        applyFilter,
        clearFilters,
    } = useServerTable({
        route: () => purchaseIndex.url(),
        pagination,
        filters,
        filterWithParams: false,
    });

    const selectedSupplier = useMemo(
        () =>
            suppliers.find(
                (s) => String(s.id) === filters.supplier_id,
            ) ?? null,
        [suppliers, filters.supplier_id],
    );

    const fetchItems = useCallback((purchase: Purchase) => {
        if (loadedItems[purchase.id] || loadingItems[purchase.id]) {
            return;
        }

        setLoadingItems((prev) => ({ ...prev, [purchase.id]: true }));

        fetch(purchaseItems.url(purchase.id))
            .then((res) => res.json())
            .then((data) => {
                setLoadedItems((prev) => ({
                    ...prev,
                    [purchase.id]: data.items ?? [],
                }));
            })
            .catch(() => {
                setLoadedItems((prev) => ({ ...prev, [purchase.id]: [] }));
            })
            .finally(() => {
                setLoadingItems((prev) => ({ ...prev, [purchase.id]: false }));
            });
    }, [loadedItems, loadingItems]);

    function handleDelete() {
        if (!deleting) {
            return;
        }

        router.delete(destroy.url(deleting.id), {
            onSuccess: () => setDeleting(null),
        });
    }

    const filterToolbar = (
        <FilterPopover
            open={filterOpen}
            onOpenChange={setFilterOpen}
            filters={filters}
            hasActiveFilters={Boolean(filters.supplier_id)}
            onClear={clearFilters}
        >
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Supplier
                </label>
                <Combobox
                    items={suppliers}
                    itemToStringLabel={(supplier) => supplier.name}
                    value={selectedSupplier}
                    onValueChange={(value) =>
                        applyFilter(
                            'supplier_id',
                            value ? String(value.id) : '',
                        )
                    }
                >
                    <ComboboxInput
                        placeholder="Pilih supplier..."
                        className="w-full"
                    />
                    <ComboboxContent>
                        <ComboboxEmpty>
                            Tidak ada supplier ditemukan.
                        </ComboboxEmpty>
                        <ComboboxList>
                            {(supplier) => (
                                <ComboboxItem value={supplier}>
                                    {supplier.name}
                                </ComboboxItem>
                            )}
                        </ComboboxList>
                    </ComboboxContent>
                </Combobox>
            </div>
        </FilterPopover>
    );

    return (
        <>
            <Head title="Belanja" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Belanja"
                    description={
                        highlight && (
                            <p className="mt-1 text-sm text-muted-foreground">
                                Menampilkan belanja dari notifikasi.
                                <button
                                    onClick={() => {
                                        router.get(
                                            purchaseIndex.url(),
                                            {},
                                            {
                                                replace: true,
                                                preserveState: true,
                                            },
                                        );
                                    }}
                                    className="ml-1 text-primary underline underline-offset-4 hover:text-primary/80"
                                >
                                    Tampilkan semua
                                </button>
                            </p>
                        )
                    }
                    actions={
                        can('purchases.create') ? (
                            <Button asChild>
                                <Link href={purchaseCreate.url()}>
                                    <Plus className="h-4 w-4" />
                                    Tambah
                                </Link>
                            </Button>
                        ) : undefined
                    }
                />

                <CardTable
                    data={purchases.data}
                    getItemKey={(p) => p.id}
                    expandedKeys={expand.expandedKeys}
                    onToggleExpand={(key) => {
                        const p = purchases.data.find((r) => r.id === key);
                        const isCurrentlyExpanded = expand.expandedKeys === 'all' || expand.expandedKeys.has(key);
                        if (p && !isCurrentlyExpanded) {
                            fetchItems(p);
                        }
                        expand.toggleExpand(key);
                    }}
                    searchValue={search}
                    onSearchChange={handleSearchChange}

                    toolbar={filterToolbar}
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    renderCard={({
                        item,
                        index,
                        isExpanded,
                        onToggleExpand,
                    }) => (
                        <PurchaseCardRow
                            purchase={item}
                            index={
                                (pagination.current_page - 1) *
                                pagination.per_page +
                                index +
                                1
                            }
                            isExpanded={isExpanded}
                            onToggleExpand={onToggleExpand}
                            onEdit={(p) => {
                                router.visit(purchaseEdit.url(p.id));
                            }}
                            onDelete={(p) => setDeleting(p)}
                        />
                    )}
                    renderSubContent={(purchase) => (
                        <PurchaseItemSubRow
                            purchase={purchase}
                            items={loadedItems[purchase.id] ?? []}
                            isLoading={loadingItems[purchase.id] ?? false}
                        />
                    )}
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Belanja"
                    description={(purchase) =>
                        `Apakah Anda yakin ingin menghapus belanja dari "${purchase.supplier?.name}"? Stok akan dikembalikan. Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}
