<script lang="ts">
    import { Button } from "$lib/components/ui/button";
    import { Input } from "$lib/components/ui/input";
    import * as Dialog from "$lib/components/ui/dialog";
    import * as Table from "$lib/components/ui/table";
    import { toast } from "svelte-sonner";
    import { Search, Loader2, Hash } from "lucide-svelte";
    import { getUSTariffFractions, type USTariffFraction } from "$lib/api/dashboard/a76/general_catalogs/us-tariff-fractions";
    import { companyStore } from "$lib/stores/company.svelte";

    // --- PROPS ---
    let { 
        open = $bindable(false), 
        onSelect 
    }: { 
        open: boolean, 
        onSelect: (item: USTariffFraction) => void 
    } = $props();

    // --- ESTADO ---
    let items = $state<USTariffFraction[]>([]);
    let loading = $state(false);
    let searchTerm = $state("");
    let loaded = $state(false);

    // Filtro local
    let filteredItems = $derived(
        items.filter(i => 
            (i.code || "").includes(searchTerm) || 
            (i.description || "").toLowerCase().includes(searchTerm.toLowerCase())
        )
    );

    // Cargar datos al abrir
    $effect(() => {
        if (open && !loaded && companyStore.activeCompany?.id) {
            loadFractions();
        }
    });

    async function loadFractions() {
        if (!companyStore.activeCompany?.id) {
            toast.error("No hay empresa seleccionada");
            return;
        }
        
        loading = true;
        try {
            const response = await getUSTariffFractions(1, 1000, companyStore.activeCompany.id);
            
            if (response.error) {
                console.error("Error al cargar fracciones americanas:", response.error);
                toast.error(`Error: ${response.error}`);
                return;
            }

            if (response.data?.items) {
                items = response.data.items;
                loaded = true;
            } else {
                console.warn("No se encontraron fracciones americanas:", response);
                toast.info("No se encontraron fracciones americanas registradas");
            }
        } catch (e: any) {
            console.error("Excepción cargando fracciones americanas:", e);
            toast.error(`Error de conexión: ${e.message || e}`);
        } finally {
            loading = false;
        }
    }

    function handleSelect(item: USTariffFraction) {
        if (onSelect) onSelect(item);
        open = false;
    }
</script>

<Dialog.Root bind:open={open}>
    <Dialog.Content class="sm:max-w-[800px] max-h-[80vh] flex flex-col">
        <Dialog.Header>
            <Dialog.Title>Seleccionar Fracción Americana</Dialog.Title>
            <Dialog.Description>
                Seleccione la fracción arancelaria (HTS) del catálogo.
            </Dialog.Description>
        </Dialog.Header>

        <div class="relative w-full my-2">
            <Search class="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
            <Input 
                type="search" 
                placeholder="Buscar por código o descripción..." 
                class="pl-9" 
                bind:value={searchTerm}
            />
        </div>

        <div class="flex-1 overflow-y-auto border rounded-md min-h-[300px]">
            {#if loading}
                <div class="flex flex-col items-center justify-center h-48 gap-2 text-muted-foreground">
                    <Loader2 class="h-8 w-8 animate-spin text-primary" />
                    <p>Cargando catálogo...</p>
                </div>
            {:else if filteredItems.length === 0}
                <div class="flex flex-col items-center justify-center h-48 text-muted-foreground">
                    <p>No se encontraron fracciones.</p>
                </div>
            {:else}
                <Table.Root>
                    <Table.Header>
                        <Table.Row>
                            <Table.Head class="w-[150px]">Código (HTS)</Table.Head>
                            <Table.Head>Descripción</Table.Head>
                        </Table.Row>
                    </Table.Header>
                    <Table.Body>
                        {#each filteredItems as item}
                            <Table.Row 
                                class="cursor-pointer hover:bg-accent/50 transition-colors"
                                onclick={() => handleSelect(item)}
                            >
                                <Table.Cell>
                                    <div class="flex items-center gap-2">
                                        <Hash class="h-3 w-3 text-blue-500" />
                                        <span class="font-mono font-bold text-blue-600 dark:text-blue-400">
                                            {item.code}
                                        </span>
                                    </div>
                                </Table.Cell>
                                <Table.Cell class="font-medium text-sm">
                                    {item.description || '-'}
                                </Table.Cell>
                            </Table.Row>
                        {/each}
                    </Table.Body>
                </Table.Root>
            {/if}
        </div>

        <Dialog.Footer>
            <div class="text-xs text-muted-foreground self-center mr-auto">
                {filteredItems.length} registros encontrados
            </div>
            <Button variant="outline" onclick={() => open = false}>Cancelar</Button>
        </Dialog.Footer>
    </Dialog.Content>
</Dialog.Root>
