<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 { Search, Loader2, Globe } from "lucide-svelte";
    import { countriesApi, type Country } from "$lib/api/dashboard/reference_data/countries";
    import { companyStore } from "$lib/stores/company.svelte";
    import { toast } from "svelte-sonner";

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

    // --- ESTADO ---
    let items = $state<Country[]>([]);
    let loading = $state(false);
    let loadingMore = $state(false);
    let searchTerm = $state("");
    let previousSearchTerm = "";
    let page = $state(1);
    let pageSize = 50;
    let hasMore = $state(true);
    let totalItems = $state(0);
    let observer: IntersectionObserver | null = null;
    let bottomSentinel: HTMLElement | null = $state(null);
    let searchTimeout: any;
    let isInitialized = false;

    // Cargar datos iniciales al abrir
    $effect(() => {
        if (open && !isInitialized) {
            isInitialized = true;
            previousSearchTerm = searchTerm;
            resetAndLoad();
        } else if (!open) {
            isInitialized = false;
        }
    });

    // Manejar búsqueda con debouncing - solo cuando cambia el término
    $effect(() => {
        const term = searchTerm;
        
        // Solo resetear si el término cambió y ya estamos inicializados
        if (isInitialized && term !== previousSearchTerm) {
            if (searchTimeout) clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                previousSearchTerm = term;
                resetAndLoad();
            }, 500);
        }
    });

    // Configurar IntersectionObserver para infinite scroll
    $effect(() => {
        if (bottomSentinel && hasMore && !loading && !loadingMore && open) {
            if (observer) observer.disconnect();
            
            observer = new IntersectionObserver((entries) => {
                if (entries[0].isIntersecting && hasMore && !loading && !loadingMore) {
                    loadMore();
                }
            }, { threshold: 0.1 });
            
            observer.observe(bottomSentinel);
        }
        
        return () => {
            if (observer) observer.disconnect();
        };
    });

    async function resetAndLoad() {
        page = 1;
        items = [];
        hasMore = true;
        await loadCountries(true);
    }

    async function loadMore() {
        if (!hasMore || loading || loadingMore) return;
        page += 1;
        await loadCountries(false);
    }

    async function loadCountries(isInitial: boolean) {
        if (isInitial) {
            loading = true;
        } else {
            loadingMore = true;
        }

        try {
            const companyId = companyStore.activeCompany?.id;
            if (!companyId) {
                toast.error("No hay una empresa activa seleccionada");
                loading = false;
                loadingMore = false;
                return;
            }

            const response = await countriesApi.list(companyId, page, pageSize, searchTerm);
            
            if (response.error) {
                toast.error(`Error: ${response.error}`);
                hasMore = false;
                return;
            }

            const newItems = response.data?.items || [];
            totalItems = response.data?.total || 0;
            
            if (isInitial) {
                items = newItems;
            } else {
                items = [...items, ...newItems];
            }

            hasMore = items.length < totalItems && newItems.length > 0;

        } catch (e: any) {
            console.error("Error loading countries:", e);
            toast.error("Error al conectar con el servidor");
            hasMore = false;
        } finally {
            loading = false;
            loadingMore = false;
        }
    }

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

<Dialog.Root bind:open={open}>
    <Dialog.Content class="sm:max-w-[900px] max-h-[90vh] flex flex-col z-[300]">
        <Dialog.Header>
            <Dialog.Title>Seleccionar País</Dialog.Title>
            <Dialog.Description>
                Seleccione el país de origen del catálogo. Escrolea para ver más.
            </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 && items.length === 0}
                <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 items.length === 0}
                <div class="flex flex-col items-center justify-center h-48 text-muted-foreground">
                    <p>No se encontraron países.</p>
                </div>
            {:else}
                <Table.Root>
                    <Table.Header>
                        <Table.Row>
                            <Table.Head class="w-[80px]">M3</Table.Head>
                            <Table.Head class="w-[80px]">MEX</Table.Head>
                            <Table.Head class="w-[80px]">AME</Table.Head>
                            <Table.Head>Descripción ES</Table.Head>
                            <Table.Head>Description EN</Table.Head>
                        </Table.Row>
                    </Table.Header>
                    <Table.Body>
                        {#each items as item}
                            <Table.Row 
                                class="cursor-pointer hover:bg-accent/50 transition-colors"
                                onclick={() => handleSelect(item)}
                            >
                                <Table.Cell>
                                    <div class="flex items-center gap-1">
                                        <Globe class="h-3 w-3 text-blue-500" />
                                        <span class="font-mono font-bold text-xs">
                                            {item.m3_key}
                                        </span>
                                    </div>
                                </Table.Cell>
                                <Table.Cell class="font-mono text-xs">
                                    {item.mex_key}
                                </Table.Cell>
                                <Table.Cell class="font-mono text-xs">
                                    {item.ame_key}
                                </Table.Cell>
                                <Table.Cell class="font-medium text-sm">
                                    {item.description_es}
                                </Table.Cell>
                                <Table.Cell class="text-sm text-muted-foreground italic">
                                    {item.description_en}
                                </Table.Cell>
                            </Table.Row>
                        {/each}
                    </Table.Body>
                </Table.Root>
                
                <!-- Sentinel for Infinite Scroll -->
                <div bind:this={bottomSentinel} class="h-10 flex items-center justify-center">
                    {#if loadingMore}
                        <Loader2 class="h-5 w-5 animate-spin text-muted-foreground" />
                    {/if}
                </div>
            {/if}
        </div>

        <Dialog.Footer>
            <div class="text-xs text-muted-foreground self-center mr-auto">
                {items.length} de {totalItems} registros
            </div>
            {#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>
