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 { FilterPopover } from '@/components/data-display';
import { DeleteConfirmDialog } from '@/components/dialogs';
import type { ImagePreviewItem } from '@/components/dialogs';
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 rawMaterialCreate,
    edit as rawMaterialEdit,
    index as rawMaterialIndex,
    toggleStatus,
    variants as rawMaterialVariants,
} from '@/routes/admin/master/raw-materials';
import {
    destroy as variantDestroy
} from '@/routes/admin/master/raw-materials/variants';
import type { RawMaterial, RawMaterialVariant } from './columns';
import { RawMaterialCardRow } from './raw-material-card';
import { RawMaterialVariantSubRow } from './variant/sub-row';

type Props = {
    rawMaterials: {
        data: RawMaterial[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    rawMaterialNames: string[];
    filters: {
        is_active?: string;
        name?: string;
        stock?: string;
    };
    highlight?: number;
};

export default function RawMaterialIndex({ rawMaterials, rawMaterialNames, filters, highlight }: Props) {
    const { can } = useCan();
    const [deleting, setDeleting] = useState<RawMaterial | null>(null);
    const [deletingVariant, setDeletingVariant] = useState<{
        rawMaterial: RawMaterial;
        variant: RawMaterialVariant;
    } | null>(null);
    const [loadedVariants, setLoadedVariants] = useState<Record<number, RawMaterialVariant[]>>({});
    const [loadingVariants, setLoadingVariants] = useState<Record<number, boolean>>({});
    const expand = useCardTableExpand(false);

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

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

    const sortedRawMaterialNames = useMemo(
        () => [...rawMaterialNames].sort(),
        [rawMaterialNames],
    );

    const fetchVariants = useCallback((rawMaterial: RawMaterial) => {
        if (loadedVariants[rawMaterial.id] || loadingVariants[rawMaterial.id]) {
            return;
        }

        setLoadingVariants((prev) => ({ ...prev, [rawMaterial.id]: true }));

        fetch(rawMaterialVariants.url(rawMaterial.id))
            .then((res) => res.json())
            .then((data) => {
                setLoadedVariants((prev) => ({
                    ...prev,
                    [rawMaterial.id]: data.variants ?? [],
                }));
            })
            .catch(() => {
                setLoadedVariants((prev) => ({ ...prev, [rawMaterial.id]: [] }));
            })
            .finally(() => {
                setLoadingVariants((prev) => ({ ...prev, [rawMaterial.id]: false }));
            });
    }, [loadedVariants, loadingVariants]);

    const allPreviewItems: ImagePreviewItem[] = useMemo(
        () =>
            Object.entries(loadedVariants).flatMap(([rmId, variants]) =>
                variants
                    .filter((v) => v.photo_url)
                    .map((v) => ({
                        id: `${rmId}-${v.id}`,
                        src: v.photo_url,
                        title: v.variant,
                        description: `Stok: ${v.formatted_stock}`,
                    }))
            ),
        [loadedVariants],
    );

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

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

    function handleDeleteVariant() {
        if (!deletingVariant) {
            return;
        }

        router.delete(
            variantDestroy.url({
                rawMaterial: deletingVariant.rawMaterial.id,
                variant: deletingVariant.variant.id,
            }),
            {
                onSuccess: () => setDeletingVariant(null),
            },
        );
    }

    const filterToolbar = (
        <FilterPopover
            open={filterOpen}
            onOpenChange={setFilterOpen}
            filters={filters}
            hasActiveFilters={Boolean(filters.is_active || filters.name || filters.stock)}
            onClear={clearFilters}
        >
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Nama Bahan Baku
                </label>
                <Combobox
                    items={sortedRawMaterialNames}
                    value={filters.name ?? ''}
                    onValueChange={(value) =>
                        applyFilter('name', (value as string) ?? '')
                    }
                >
                    <ComboboxInput
                        placeholder="Pilih bahan baku..."
                        className="w-full"
                    />
                    <ComboboxContent>
                        <ComboboxEmpty>
                            Tidak ada bahan baku ditemukan.
                        </ComboboxEmpty>
                        <ComboboxList>
                            {(name) => (
                                <ComboboxItem key={name} value={name}>{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.is_active ?? 'all'}
                    onValueChange={(value) => applyFilter('is_active', value)}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Semua Status" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">Semua Status</SelectItem>
                        <SelectItem value="true">Aktif</SelectItem>
                        <SelectItem value="false">Non Aktif</SelectItem>
                    </SelectContent>
                </Select>
            </div>

            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">Stok</label>
                <Select
                    value={filters.stock ?? 'all'}
                    onValueChange={(value) => applyFilter('stock', value)}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Semua Stok" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">Semua Stok</SelectItem>
                        <SelectItem value="empty">Habis</SelectItem>
                        <SelectItem value="low">
                            Menipis (di bawah 10)
                        </SelectItem>
                    </SelectContent>
                </Select>
            </div>
        </FilterPopover>
    );

    return (
        <>
            <Head title="Bahan Baku" />

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

                <CardTable
                    data={rawMaterials.data}
                    getItemKey={(rm) => rm.id}
                    expandedKeys={expand.expandedKeys}
                    onToggleExpand={(key) => {
                        const rm = rawMaterials.data.find((r) => r.id === key);
                        const isCurrentlyExpanded = expand.expandedKeys === 'all' || expand.expandedKeys.has(key);

                        if (rm && !isCurrentlyExpanded) {
                            fetchVariants(rm);
                        }

                        expand.toggleExpand(key);
                    }}
                    searchValue={search}
                    onSearchChange={handleSearchChange}

                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    toolbar={filterToolbar}
                    renderCard={({
                        item,
                        index,
                        isExpanded,
                        onToggleExpand,
                    }) => (
                        <RawMaterialCardRow
                            rawMaterial={item}
                            index={
                                (pagination.current_page - 1) *
                                pagination.per_page +
                                index +
                                1
                            }
                            isExpanded={isExpanded}
                            onToggleExpand={onToggleExpand}
                            onEdit={(rm) => {
                                router.visit(rawMaterialEdit.url(rm.id));
                            }}
                            onDelete={(rm) => setDeleting(rm)}
                            toggleStatusUrl={(id) => toggleStatus.url(id)}
                        />
                    )}
                    renderSubContent={(rawMaterial) => (
                        <RawMaterialVariantSubRow
                            rawMaterial={rawMaterial}
                            variants={loadedVariants[rawMaterial.id] ?? []}
                            isLoading={loadingVariants[rawMaterial.id] ?? false}
                            allPreviewItems={allPreviewItems}
                        />
                    )}
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Bahan Baku"
                    description={(rawMaterial) =>
                        `Apakah Anda yakin ingin menghapus bahan baku "${rawMaterial.name}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />

                <DeleteConfirmDialog
                    target={deletingVariant}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeletingVariant(null);
                        }
                    }}
                    title="Hapus Varian"
                    description={(target) =>
                        `Apakah Anda yakin ingin menghapus varian "${target.variant.variant}" dari bahan baku "${target.rawMaterial.name}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDeleteVariant}
                />
            </div>
        </>
    );
}
