import { CardTable } from '@/components/card-table';
import { DeleteConfirmDialog } from '@/components/delete-confirm-dialog';
import { FilterPopover } from '@/components/filter-popover';
import { useCardTableExpand } from '@/components/hooks/use-card-table-expand';
import { PageHeader } from '@/components/page-header';
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,
} from '@/routes/admin/manage/purchases';
import { Head, Link, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useMemo, useState } from 'react';
import type { Purchase } 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;
    };
};

export default function PurchaseIndex({
    purchases,
    filters,
    suppliers,
}: Props) {
    const { can } = useCan();
    const [deleting, setDeleting] = useState<Purchase | null>(null);
    const expand = useCardTableExpand(true);

    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],
    );

    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"
                    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={expand.toggleExpand}
                    searchValue={search}
                    onSearchChange={handleSearchChange}
                    searchPlaceholder="Cari berdasarkan supplier..."
                    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} />
                    )}
                />

                <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>
        </>
    );
}
