import { Link, router } from '@inertiajs/react';
import { Head } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useMemo, useState } from 'react';
import { CardTable } from '@/components/data-display';
import { DeleteConfirmDialog } from '@/components/dialogs';
import type { ImagePreviewItem } 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 productCreate,
    edit as productEdit,
    index as productIndex,
    toggleStatus,
    toggleFeatured as productToggleFeatured,
    approve as productApprove,
    reject as productReject,
    resubmit as productResubmit,
} from '@/routes/admin/master/products';
import {
    destroy as variantDestroy,
    edit as variantEdit,
} from '@/routes/admin/master/products/variants';
import type { Product, ProductVariant } from './columns';
import { ProductCardRow } from './product-card';
import { RejectDialog } from './reject-dialog';
import { VariantSubRow } from './variant/sub-row';

type Props = {
    products: {
        data: Product[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    categories: {
        id: number;
        name: string;
    }[];
    productNames: string[];
    filters: {
        status?: string;
        name?: string;
        stock?: string;
        category?: string;
        featured?: string;
    };
};

export default function ProductIndex({ products, categories, productNames, filters }: Props) {
    const { can } = useCan();
    const [deleting, setDeleting] = useState<Product | null>(null);
    const [deletingVariant, setDeletingVariant] = useState<{
        product: Product;
        variant: ProductVariant;
    } | null>(null);
    const [rejecting, setRejecting] = useState<Product | null>(null);
    const expand = useCardTableExpand(true);

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

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

    const sortedProductNames = useMemo(
        () => [...productNames].sort(),
        [productNames],
    );

    const allPreviewItems: ImagePreviewItem[] = useMemo(
        () =>
            products.data.flatMap((product) =>
                (product.product_variants ?? [])
                    .filter((v) => v.photo_urls?.length > 0)
                    .map((v) => ({
                        id: `${product.id}-${v.id}`,
                        src: v.photo_urls[0],
                        sources: v.photo_urls,
                        title: v.name,
                        description: `Stok Bagus: ${v.formatted_stock} | Stok Reject: ${v.formatted_reject_stock} | Stok Ecer: ${v.formatted_retail_stock}`,
                    }))
            ),
        [products.data],
    );

    const selectedCategory = useMemo(
        () => categories.find((c) => String(c.id) === filters.category) ?? null,
        [categories, filters.category],
    );

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

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

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

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

    const filterToolbar = (
        <FilterPopover
            open={filterOpen}
            onOpenChange={setFilterOpen}
            filters={filters}
            hasActiveFilters={Boolean(
                filters.status ||
                filters.name ||
                filters.stock ||
                filters.category ||
                filters.featured,
            )}
            onClear={clearFilters}
        >
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Nama Produk
                </label>
                <Combobox
                    items={sortedProductNames}
                    value={filters.name ?? ''}
                    onValueChange={(value) =>
                        applyFilter('name', (value as string) ?? '')
                    }
                >
                    <ComboboxInput
                        placeholder="Pilih produk..."
                        className="w-full"
                    />
                    <ComboboxContent>
                        <ComboboxEmpty>
                            Tidak ada produk 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.status ?? 'all'}
                    onValueChange={(value) => applyFilter('status', value)}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Semua Status" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">Semua Status</SelectItem>
                        <SelectItem value="active">Aktif</SelectItem>
                        <SelectItem value="inactive">Non Aktif</SelectItem>
                        <SelectItem value="draft">Draft</SelectItem>
                        <SelectItem value="pending">Menunggu Verifikasi</SelectItem>
                        <SelectItem value="rejected">Ditolak</SelectItem>
                    </SelectContent>
                </Select>
            </div>

            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">Stok</label>
                <span className="-mt-1 text-[0.65rem] text-muted-foreground/70">
                    Berdasarkan stok bagus
                </span>
                <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>

            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Kategori
                </label>
                <Combobox
                    items={categories}
                    itemToStringLabel={(cat) => cat.name}
                    getOptionAsValue={(cat) => String(cat.id)}
                    value={selectedCategory}
                    onValueChange={(value) =>
                        applyFilter('category', value ? String(value.id) : '')
                    }
                >
                    <ComboboxInput
                        placeholder="Pilih kategori..."
                        className="w-full"
                    />
                    <ComboboxContent>
                        <ComboboxEmpty>
                            Tidak ada kategori ditemukan.
                        </ComboboxEmpty>
                        <ComboboxList>
                            {(cat) => (
                                <ComboboxItem key={cat.id} value={cat}>
                                    {cat.name}
                                </ComboboxItem>
                            )}
                        </ComboboxList>
                    </ComboboxContent>
                </Combobox>
            </div>

            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Halaman Depan
                </label>
                <Select
                    value={filters.featured ?? 'all'}
                    onValueChange={(value) => applyFilter('featured', value)}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Semua" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">Semua</SelectItem>
                        <SelectItem value="true">Ditampilkan</SelectItem>
                        <SelectItem value="false">Tidak Ditampilkan</SelectItem>
                    </SelectContent>
                </Select>
            </div>
        </FilterPopover>
    );

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Produk"
                    actions={
                        can('products.create') ? (
                            <Button asChild>
                                <Link href={productCreate.url()}>
                                    <Plus className="h-4 w-4" />
                                    Tambah
                                </Link>
                            </Button>
                        ) : undefined
                    }
                />

                <CardTable
                    data={products.data}
                    getItemKey={(p) => p.id}
                    expandedKeys={expand.expandedKeys}
                    onToggleExpand={expand.toggleExpand}
                    searchValue={search}
                    onSearchChange={handleSearchChange}

                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    toolbar={filterToolbar}
                    renderCard={({
                        item,
                        index,
                        isExpanded,
                        onToggleExpand,
                    }) => (
                        <ProductCardRow
                            product={item}
                            index={
                                (pagination.current_page - 1) *
                                pagination.per_page +
                                index +
                                1
                            }
                            isExpanded={isExpanded}
                            onToggleExpand={onToggleExpand}
                            onEdit={(p) => {
                                router.visit(productEdit.url(p.id));
                            }}
                            onDelete={(p) => setDeleting(p)}
                            onReject={(p) => setRejecting(p)}
                            toggleStatusUrl={(id) => toggleStatus.url(id)}
                            toggleFeaturedUrl={(id) => productToggleFeatured.url(id)}
                            approveUrl={(id) => productApprove.url(id)}
                            resubmitUrl={(id) => productResubmit.url(id)}
                        />
                    )}
                    renderSubContent={(product) => (
                        <VariantSubRow
                            product={product}
                            allPreviewItems={allPreviewItems}
                            onEditVariant={(p, v) => {
                                router.visit(
                                    variantEdit.url({
                                        product: p.id,
                                        variant: v.id,
                                    }),
                                );
                            }}
                            onDeleteVariantClick={(p, v) =>
                                setDeletingVariant({ product: p, variant: v })
                            }
                        />
                    )}
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Produk"
                    description={(product) =>
                        `Apakah Anda yakin ingin menghapus produk "${product.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.name}" dari produk "${target.product.name}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDeleteVariant}
                />

                <RejectDialog
                    product={rejecting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setRejecting(null);
                        }
                    }}
                    rejectUrl={(id) => productReject.url(id)}
                />
            </div>
        </>
    );
}
