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 {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useCan } from '@/hooks/use-can';
import { useServerTable } from '@/hooks/use-server-table';
import {
    destroy,
    create as cuttingCreate,
    index as cuttingIndex,
    edit as cuttingEdit,
    materials as cuttingMaterials,
    complete as cuttingComplete,
} from '@/routes/admin/manage/cuttings';
import type { Cutting, CuttingMaterialDetail, CuttingCombination } from './columns';
import { CuttingCardRow } from './cutting-card';
import { CuttingItemSubRow } from './cutting-sub-row';

type Props = {
    cuttings: {
        data: Cutting[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    filters: {
        product_name?: string;
        status?: string;
    };
    filterOptions: {
        statusOptions: Array<{ value: string; label: string }>;
        productNames: Array<{ product_name: string }>;
    };
    highlight?: number;
};

export default function CuttingIndex({
    cuttings,
    filters,
    filterOptions,
    highlight,
}: Props) {
    const { can } = useCan();
    const [deleting, setDeleting] = useState<Cutting | null>(null);
    const [completing, setCompleting] = useState<Cutting | null>(null);
    const [loadedMaterials, setLoadedMaterials] = useState<Record<number, CuttingMaterialDetail[]>>({});
    const [loadedCombinations, setLoadedCombinations] = useState<Record<number, CuttingCombination[]>>({});
    const [loadingMaterials, setLoadingMaterials] = useState<Record<number, boolean>>({});
    const expand = useCardTableExpand(false);

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

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

    const hasActiveFilters = Boolean(filters.product_name || filters.status);

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

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

    function handleComplete() {
        if (!completing) {
            return;
        }

        router.patch(cuttingComplete.url(completing.id), {}, {
            onSuccess: () => setCompleting(null),
        });
    }

    const selectedProductName = useMemo(
        () =>
            filterOptions.productNames.find(
                (p) => p.product_name === filters.product_name,
            ) ?? null,
        [filterOptions.productNames, filters.product_name],
    );

    const fetchMaterials = useCallback((cutting: Cutting) => {
        if (loadedMaterials[cutting.id] || loadingMaterials[cutting.id]) {
            return;
        }

        setLoadingMaterials((prev) => ({ ...prev, [cutting.id]: true }));

        fetch(cuttingMaterials.url(cutting.id))
            .then((res) => res.json())
            .then((data) => {
                setLoadedMaterials((prev) => ({
                    ...prev,
                    [cutting.id]: data.materials ?? [],
                }));
                setLoadedCombinations((prev) => ({
                    ...prev,
                    [cutting.id]: data.combinations ?? [],
                }));
            })
            .catch(() => {
                setLoadedMaterials((prev) => ({ ...prev, [cutting.id]: [] }));
                setLoadedCombinations((prev) => ({ ...prev, [cutting.id]: [] }));
            })
            .finally(() => {
                setLoadingMaterials((prev) => ({ ...prev, [cutting.id]: false }));
            });
    }, [loadedMaterials, loadingMaterials]);

    const filterToolbar = (
        <FilterPopover
            open={filterOpen}
            onOpenChange={setFilterOpen}
            filters={filters}
            hasActiveFilters={hasActiveFilters}
            onClear={clearFilters}
        >
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Nama Produk
                </label>
                <Combobox
                    items={filterOptions.productNames}
                    itemToStringLabel={(product) => product.product_name}
                    value={selectedProductName}
                    onValueChange={(value) =>
                        applyFilter(
                            'product_name',
                            value ? value.product_name : '',
                        )
                    }
                >
                    <ComboboxInput
                        placeholder="Pilih nama produk..."
                        className="w-full"
                    />
                    <ComboboxContent>
                        <ComboboxEmpty>
                            Tidak ada produk ditemukan.
                        </ComboboxEmpty>
                        <ComboboxList>
                            {(product) => (
                                <ComboboxItem value={product}>
                                    {product.product_name}
                                </ComboboxItem>
                            )}
                        </ComboboxList>
                    </ComboboxContent>
                </Combobox>
            </div>
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Status
                </label>
                <Select
                    value={filters.status ?? ''}
                    onValueChange={(value) =>
                        applyFilter('status', value)
                    }
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Semua status" />
                    </SelectTrigger>
                    <SelectContent>
                        {filterOptions.statusOptions.map((opt) => (
                            <SelectItem key={opt.value} value={opt.value}>
                                {opt.label}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            </div>
        </FilterPopover>
    );

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

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

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

                    toolbar={filterToolbar}
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    rowClassName={(c) =>
                        c.status === 'in_progress'
                            ? 'border-l-4 border-l-yellow-500'
                            : ''
                    }
                    renderCard={({
                        item,
                        index,
                        isExpanded,
                        onToggleExpand,
                    }) => (
                        <CuttingCardRow
                            cutting={item}
                            index={
                                (pagination.current_page - 1) *
                                    pagination.per_page +
                                index +
                                1
                            }
                            isExpanded={isExpanded}
                            onToggleExpand={onToggleExpand}
                            onComplete={(c) => setCompleting(c)}
                            onEdit={(c) => {
                                router.visit(cuttingEdit.url(c.id));
                            }}
                            onDelete={(c) => setDeleting(c)}
                        />
                    )}
                    renderSubContent={(cutting) => (
                        <CuttingItemSubRow
                            cutting={cutting}
                            materials={loadedMaterials[cutting.id] ?? []}
                            combinations={loadedCombinations[cutting.id] ?? []}
                            isLoading={loadingMaterials[cutting.id] ?? false}
                        />
                    )}
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Cutting"
                    description={(cutting) =>
                        `Apakah Anda yakin ingin menghapus cutting "${cutting.cutting_results?.[0]?.product_name ?? '-'}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />

                <DeleteConfirmDialog
                    target={completing}
                    onOpenChange={(open) => {
                        if (!open) {
                            setCompleting(null);
                        }
                    }}
                    title="Selesaikan Cutting"
                    description={(cutting) =>
                        `Apakah Anda yakin ingin menyelesaikan cutting "${cutting.cutting_results?.[0]?.product_name ?? '-'}"?`
                    }
                    confirmLabel="Selesaikan"
                    onConfirm={handleComplete}
                />
            </div>
        </>
    );
}
