import { Head, Link, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useCallback, useState } from 'react';
import { CardTable } from '@/components/data-display';
import { DeleteConfirmDialog } from '@/components/dialogs';
import { useCardTableExpand } from '@/components/hooks/use-card-table-expand';
import { PageHeader } from '@/components/layout';
import { Button } from '@/components/ui/button';
import { useCan } from '@/hooks/use-can';
import { useServerTable } from '@/hooks/use-server-table';
import {
    destroy,
    create as restockCreate,
    index as restockIndex,
    edit as restockEdit,
    items as restockItems,
} from '@/routes/admin/manage/restocks';
import type { Restock, RestockItem } from './columns';
import { RestockCardRow } from './restock-card';
import { RestockItemSubRow } from './restock-sub-row';

type Props = {
    restocks: {
        data: Restock[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    highlight?: number;
};

export default function RestockIndex({ restocks, highlight }: Props) {
    const { can } = useCan();
    const [deleting, setDeleting] = useState<Restock | null>(null);
    const [loadedItems, setLoadedItems] = useState<Record<number, RestockItem[]>>({});
    const [loadingItems, setLoadingItems] = useState<Record<number, boolean>>({});
    const expand = useCardTableExpand(false);

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

    const {
        search,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
    } = useServerTable({
        route: () => restockIndex.url(),
        pagination,
    });

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

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

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

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

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

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

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

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

                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    renderCard={({
                        item,
                        index,
                        isExpanded,
                        onToggleExpand,
                    }) => (
                        <RestockCardRow
                            restock={item}
                            index={
                                (pagination.current_page - 1) *
                                    pagination.per_page +
                                index +
                                1
                            }
                            isExpanded={isExpanded}
                            onToggleExpand={onToggleExpand}
                            onEdit={(r) => {
                                router.visit(restockEdit.url(r.id));
                            }}
                            onDelete={(r) => setDeleting(r)}
                        />
                    )}
                    renderSubContent={(restock) => (
                        <RestockItemSubRow
                            restock={restock}
                            items={loadedItems[restock.id] ?? []}
                            isLoading={loadingItems[restock.id] ?? false}
                        />
                    )}
                />

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