<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 { Search, Loader2, Tag, Ruler } from "lucide-svelte";
    import { classesApi, type A76Class } from "$lib/api/dashboard/a76/classes"; // Ajusta ruta
    import { companyStore } from "$lib/stores/company.svelte";

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

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

    // Filtro local: Busca por Clave (class_code) o Descripción (description_es)
    let filteredItems = $derived(
        items.filter(i => 
            (i.class_code || "").toLowerCase().includes(searchTerm.toLowerCase()) || 
            (i.description_es || "").toLowerCase().includes(searchTerm.toLowerCase())
        )
    );

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

    async function loadClasses() {
        if (!companyStore.activeCompany?.id) return;
        
        loading = true;
        try {
            
            const res = await classesApi.list({ 
                company_id: companyStore.activeCompany.id,
                page: 1,
                page_size: 100
            });
            
           
            const data = (res as any).data || res;
            
            
            const list = data.items || data.classes || [];
            
            if (Array.isArray(list)) {
                items = list;
                loaded = true;
            } else {
                console.warn("No encontré lista de clases en la respuesta:", data);
            }

        } catch (e) {
            console.error("Error cargando clases:", e);
        } finally {
            loading = false;
        }
    }

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

<Dialog.Root bind:open={open}>
    <Dialog.Content class="sm:max-w-[700px] max-h-[80vh] flex flex-col">
        <Dialog.Header>
            <Dialog.Title>Seleccionar Clase (Anexo 24)</Dialog.Title>
            <Dialog.Description>
                Seleccione la clasificación del material.
            </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 Clave 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 clases.</p>
                </div>
            {:else}
                <table class="w-full text-sm">
                    <thead class="bg-muted/50 sticky top-0 backdrop-blur-sm">
                        <tr class="text-left border-b">
                            <th class="p-3 font-medium text-muted-foreground w-[100px]">Clave</th>
                            <th class="p-3 font-medium text-muted-foreground">Descripción</th>
                            <th class="p-3 font-medium text-muted-foreground w-[80px]">UM</th>
                        </tr>
                    </thead>
                    <tbody>
                        {#each filteredItems as item}
                            <tr 
                                class="border-b hover:bg-accent/50 transition-colors cursor-pointer"
                                onclick={() => handleSelect(item)}
                            >
                                <td class="p-3">
                                    <span class="font-mono font-bold text-primary bg-primary/10 px-2 py-1 rounded text-xs">
                                        {item.class_code}
                                    </span>
                                </td>
                                
                                <td class="p-3">
                                    <div class="flex items-center gap-2">
                                        <Tag class="h-3 w-3 text-muted-foreground shrink-0" />
                                        <span class="truncate max-w-[300px]" title={item.description_es || ''}>
                                            {item.description_es || 'Sin descripción'}
                                        </span>
                                    </div>
                                </td>

                                <td class="p-3">
                                    <div class="flex items-center gap-1 text-xs text-muted-foreground">
                                        <Ruler class="h-3 w-3" />
                                        {item.unit_of_measure || '-'}
                                    </div>
                                </td>
                            </tr>
                        {/each}
                    </tbody>
                </table>
            {/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>