import { Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useCallback, useState } from 'react';
import { CardTable } from '@/components/card-table';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { useCardTableExpand } from '@/components/hooks/use-card-table-expand';
import { Button } from '@/components/ui/button';
import {
    destroy,
    create as restockCreate,
    index as restockIndex,
    edit as restockEdit,
} from '@/routes/admin/manage/restocks';
import type { Restock } 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;
    };
};

export default function RestockIndex({ restocks }: Props) {
    const [deleting, setDeleting] = useState<Restock | null>(null);
    const [search, setSearch] = useState('');
    const expand = useCardTableExpand(true);

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

    function handlePageChange(page: number) {
        router.get(
            restockIndex.url(),
            {
                page,
                per_page: pagination.per_page,
                search,
            },
            { preserveState: true, replace: true },
        );
    }

    function handlePerPageChange(perPage: number) {
        router.get(
            restockIndex.url(),
            {
                page: 1,
                per_page: perPage,
                search,
            },
            { preserveState: true, replace: true },
        );
    }

    const handleSearchChange = useCallback(
        (value: string) => {
            setSearch(value);
            router.get(
                restockIndex.url(),
                {
                    page: 1,
                    per_page: pagination.per_page,
                    search: value,
                },
                { preserveState: true, replace: true },
            );
        },
        [pagination.per_page],
    );

    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">
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-semibold tracking-tight">
                            Restock
                        </h2>
                    </div>
                    <Button asChild>
                        <a href={restockCreate.url()}>
                            <Plus className="h-4 w-4" />
                            Tambah
                        </a>
                    </Button>
                </div>

                <CardTable
                    data={restocks.data}
                    getItemKey={(r) => r.id}
                    expandedKeys={expand.expandedKeys}
                    onToggleExpand={expand.toggleExpand}
                    searchValue={search}
                    onSearchChange={handleSearchChange}
                    searchPlaceholder="Cari berdasarkan produk..."
                    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) => {
                                window.location.href = restockEdit.url(r.id);
                            }}
                            onDelete={(r) => setDeleting(r)}
                        />
                    )}
                    renderSubContent={(restock) => (
                        <RestockItemSubRow restock={restock} />
                    )}
                />

                <ConfirmDialog
                    open={deleting !== null}
                    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."
                    confirmLabel="Hapus"
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}
