import { Head, Link, router } from '@inertiajs/react';
import { ClipboardCheck, Plus, Send, XCircle } 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 { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { useCan } from '@/hooks/use-can';
import { useServerTable } from '@/hooks/use-server-table';
import {
    destroy,
    create as stokOpnameCreate,
    index as stokOpnameIndex,
    edit as stokOpnameEdit,
    items as stokOpnameItems,
    submit as stokOpnameSubmit,
    verify as stokOpnameVerify,
    reject as stokOpnameReject,
    cancel as stokOpnameCancel,
} from '@/routes/admin/manage/stok-opnames';
import type { StokOpname, StokOpnameItem, StokOpnameStatus } from './columns';
import { StokOpnameCardRow } from './stok-opname-card';
import { StokOpnameItemSubRow } from './stok-opname-sub-row';

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

const STATUS_CONFIG: Record<StokOpnameStatus, { label: string; className: string }> = {
    draft: { label: 'Draft', className: 'bg-gray-100 text-gray-800 hover:bg-gray-100' },
    in_progress: { label: 'Diajukan', className: 'bg-blue-100 text-blue-800 hover:bg-blue-100' },
    completed: { label: 'Selesai', className: 'bg-yellow-100 text-yellow-800 hover:bg-yellow-100' },
    verified: { label: 'Terverifikasi', className: 'bg-green-100 text-green-800 hover:bg-green-100' },
    cancelled: { label: 'Dibatalkan', className: 'bg-red-100 text-red-800 hover:bg-red-100' },
};

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

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

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

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

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

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

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

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

    function handleSubmit(stokOpname: StokOpname) {
        router.patch(stokOpnameSubmit.url(stokOpname.id));
    }

    function handleVerify(stokOpname: StokOpname) {
        router.patch(stokOpnameVerify.url(stokOpname.id), {
            data: { verification_notes: '' },
        });
    }

    function handleReject(stokOpname: StokOpname) {
        router.patch(stokOpnameReject.url(stokOpname.id));
    }

    function handleCancel(stokOpname: StokOpname) {
        router.patch(stokOpnameCancel.url(stokOpname.id));
    }

    return (
        <>
            <Head title="Stok Opname" />

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

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

                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    renderCard={({
                        item,
                        index,
                        isExpanded,
                        onToggleExpand,
                    }) => (
                        <StokOpnameCardRow
                            stokOpname={item}
                            index={
                                (pagination.current_page - 1) *
                                    pagination.per_page +
                                index +
                                1
                            }
                            isExpanded={isExpanded}
                            onToggleExpand={onToggleExpand}
                            onEdit={(s) => {
                                router.visit(stokOpnameEdit.url(s.id));
                            }}
                            onDelete={(s) => setDeleting(s)}
                            onSubmit={handleSubmit}
                            onVerify={handleVerify}
                            onReject={handleReject}
                            onCancel={handleCancel}
                        />
                    )}
                    renderSubContent={(stokOpname) => (
                        <StokOpnameItemSubRow
                            stokOpname={stokOpname}
                            items={loadedItems[stokOpname.id] ?? []}
                            isLoading={loadingItems[stokOpname.id] ?? false}
                        />
                    )}
                />

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