import { Head, router } from '@inertiajs/react';
import { Filter, Plus, X } from 'lucide-react';
import { useCallback, useState } from 'react';
import { CardTable } from '@/components/card-table';
import { useCardTableExpand } from '@/components/hooks/use-card-table-expand';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { Button } from '@/components/ui/button';
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from '@/components/ui/popover';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    destroy,
    create as rawMaterialCreate,
    index as rawMaterialIndex,
    edit as rawMaterialEdit,
    toggleStatus,
} from '@/routes/admin/master/raw-materials';
import {
    destroy as variantDestroy,
    edit as variantEdit,
} 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;
    };
    filters: {
        is_active?: string;
        stock?: string;
    };
};

export default function RawMaterialIndex({ rawMaterials, filters }: Props) {
    const [deleting, setDeleting] = useState<RawMaterial | null>(null);
    const [deletingVariant, setDeletingVariant] = useState<{
        rawMaterial: RawMaterial;
        variant: RawMaterialVariant;
    } | null>(null);
    const [filterOpen, setFilterOpen] = useState(false);
    const [search, setSearch] = useState('');
    const expand = useCardTableExpand(true);
    const hasActiveFilters = filters.is_active || filters.stock;

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

    function applyFilter(key: string, value: string) {
        const newFilters = { ...filters };

        if (value === '' || value === 'all') {
            delete newFilters[key as keyof typeof newFilters];
        } else {
            newFilters[key as keyof typeof newFilters] = value;
        }

        router.get(rawMaterialIndex(), newFilters, {
            preserveState: true,
            replace: true,
        });
    }

    function clearFilters() {
        router.get(
            rawMaterialIndex(),
            {},
            {
                preserveState: true,
                replace: true,
            },
        );
        setFilterOpen(false);
    }

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

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

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

    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 = (
        <Popover open={filterOpen} onOpenChange={setFilterOpen}>
            <PopoverTrigger asChild>
                <Button variant="outline" size="sm">
                    <Filter className="h-4 w-4" />
                    Filter
                    {hasActiveFilters && (
                        <span className="ml-1 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground">
                            {Object.values(filters).filter(Boolean).length}
                        </span>
                    )}
                </Button>
            </PopoverTrigger>
            <PopoverContent className="w-64" align="end">
                <div className="flex flex-col gap-4">
                    <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">Filter</span>
                        {hasActiveFilters && (
                            <Button
                                variant="ghost"
                                size="sm"
                                className="h-6 px-2 text-xs"
                                onClick={clearFilters}
                            >
                                <X className="mr-1 h-3 w-3" />
                                Hapus Semua
                            </Button>
                        )}
                    </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>
                </div>
            </PopoverContent>
        </Popover>
    );

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

            <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">
                            Bahan Baku
                        </h2>
                    </div>
                    <Button asChild>
                        <a href={rawMaterialCreate.url()}>
                            <Plus className="h-4 w-4" />
                            Tambah
                        </a>
                    </Button>
                </div>

                <CardTable
                    data={rawMaterials.data}
                    getItemKey={(rm) => rm.id}
                    expandedKeys={expand.expandedKeys}
                    onToggleExpand={expand.toggleExpand}
                    searchValue={search}
                    onSearchChange={handleSearchChange}
                    searchPlaceholder="Cari bahan baku..."
                    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) => {
                                window.location.href = rawMaterialEdit.url(rm.id);
                            }}
                            onDelete={(rm) => setDeleting(rm)}
                            toggleStatusUrl={(id) => toggleStatus.url(id)}
                        />
                    )}
                    renderSubContent={(rawMaterial) => (
                        <RawMaterialVariantSubRow rawMaterial={rawMaterial} />
                    )}
                />

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

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