<script lang="ts">
    import * as Dialog from "$lib/components/ui/dialog";
    import { Input } from "$lib/components/ui/input";
    import { Button } from "$lib/components/ui/button";
    import { Search, Loader2, Scale, Check } from "lucide-svelte";
    import * as Table from "$lib/components/ui/table";
    import { companyStore } from '$lib/stores/company.svelte';
    import { getUnitsOfMeasure, type UnitOfMeasure } from '$lib/api/dashboard/a76/general_catalogs/units-of-measure'; 

    let { 
        open = $bindable(false),
        onSelect,
        onClear
    }: { 
        open: boolean; 
        onSelect: (item: UnitOfMeasure) => void;
        onClear?: () => void;
    } = $props();

    let items = $state<UnitOfMeasure[]>([]);
    let allItems = $state<UnitOfMeasure[]>([]); // Store full dataset
    let loading = $state(false);
    let searchTerm = $state("");
    let wasOpen = $state(false);
    
    // Derived state for filtering
    $effect(() => {
        if (!searchTerm) {
            items = allItems;
        } else {
            const lowerTerm = searchTerm.toLowerCase();
            items = allItems.filter(item => 
                item.code.toLowerCase().includes(lowerTerm) || 
                (item.description && item.description.toLowerCase().includes(lowerTerm)) ||
                (item.description_en && item.description_en.toLowerCase().includes(lowerTerm))
            );
        }
    });

    // Cargar datos al abrir y resetear búsqueda cada vez que se abre
    $effect(() => {
        if (open && !wasOpen) {
            searchTerm = "";
            if (companyStore.activeCompany && allItems.length === 0) {
                loadData();
            }
        }
        wasOpen = open;
    });

    async function loadData() {
        if (!companyStore.activeCompany) return;
        
        loading = true;
        try {
            // Fetch everything once using the high limit
            const response = await getUnitsOfMeasure(1, 1000, companyStore.activeCompany.id, {});

            if (response.data) {
                allItems = response.data.items;
                items = allItems; // Initialize view
            }
        } catch (error) {
            console.error("Error cargando unidades:", error);
        } finally {
            loading = false;
        }
    }

    function handleSearch(e: Event) {
        const value = (e.target as HTMLInputElement).value;
        searchTerm = value;
        // No network call needed, $effect handles filtering
    }

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

<Dialog.Root bind:open>
    <Dialog.Content class="sm:max-w-[600px] z-[300]">
        <Dialog.Header>
            <Dialog.Title>Seleccionar Unidad de Medida</Dialog.Title>
            <Dialog.Description>
                Busca y selecciona una unidad del catálogo maestro.
            </Dialog.Description>
        </Dialog.Header>

        <div class="space-y-4 py-4">
            <div class="relative">
                <Search class="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input 
                    placeholder="Buscar por código (KG, PZ...) o descripción..." 
                    class="pl-8"
                    value={searchTerm}
                    oninput={handleSearch}
                />
            </div>

            <div class="rounded-md border h-[400px] overflow-auto relative">
                {#if loading}
                    <div class="absolute inset-0 bg-background/50 flex items-center justify-center z-10">
                        <Loader2 class="h-6 w-6 animate-spin text-primary" />
                    </div>
                {/if}
                
                <Table.Root>
                    <Table.Header>
                        <Table.Row>
                            <Table.Head class="w-[80px]">Código</Table.Head>
                            <Table.Head>Descripción</Table.Head>
                        </Table.Row>
                    </Table.Header>
                    <Table.Body>
                        {#if items.length === 0 && !loading}
                            <Table.Row>
                                <Table.Cell colspan={3} class="text-center h-24 text-muted-foreground">
                                    No se encontraron resultados
                                </Table.Cell>
                            </Table.Row>
                        {:else}
                            {#each items as item}
                                <Table.Row 
                                    class="cursor-pointer hover:bg-accent/50 transition-colors"
                                    onclick={() => handleSelect(item)}
                                >
                                    <Table.Cell class="font-mono font-bold">{item.code}</Table.Cell>
                                    <Table.Cell>
                                        <div class="flex flex-col">
                                            <span>{item.description || '-'}</span>
                                            {#if item.description_en}
                                                <span class="text-xs text-muted-foreground">{item.description_en}</span>
                                            {/if}
                                        </div>
                                    </Table.Cell>
                                </Table.Row>
                            {/each}
                        {/if}
                    </Table.Body>
                </Table.Root>
            </div>
            
            <div class="text-xs text-muted-foreground text-center">
                Mostrando {items.length} registros
            </div>
        </div>
        <Dialog.Footer class="flex justify-end gap-2">
            {#if onClear}
                <Button variant="ghost" onclick={() => { onClear(); open = false; }}>Quitar selección</Button>
            {/if}
            <Button variant="outline" onclick={() => (open = false)}>Cancelar</Button>
        </Dialog.Footer>
    </Dialog.Content>
</Dialog.Root>