<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, DollarSign } from "lucide-svelte";
    import { currencyTypesApi, type CurrencyType } from "$lib/api/dashboard/reference_data/currency_types";

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

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

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

    // Cargar datos al abrir
    $effect(() => {
        if (open && !loaded) {
            loadCurrencies();
        }
    });

    async function loadCurrencies() {
        loading = true;        
        try {
            // FIX: Usar API pública, sin company_id
            const response = await currencyTypesApi.list(1, 100);            
            
            if (response.error) {
                 console.error("CurrencySelectorDialog Error:", response.error);
                 toast.error(`Error al cargar monedas: ${response.error}`);
                 return;
            }

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

    function handleSelect(item: CurrencyType) {
        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 z-[300]">
        <Dialog.Header>
            <Dialog.Title>Seleccionar Moneda</Dialog.Title>
            <Dialog.Description>
                Seleccione el tipo de moneda del catálogo público.
            </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, nombre o país..." 
                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 monedas.</p>
                </div>
            {:else}
                <Table.Root>
                    <Table.Header>
                        <Table.Row>
                            <Table.Head class="w-[100px]">Código</Table.Head>
                            <Table.Head>Moneda</Table.Head>
                            <Table.Head>País</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">
                                        <DollarSign class="h-3 w-3 text-green-500" />
                                        <span class="font-mono font-bold text-primary">
                                            {item.code}
                                        </span>
                                    </div>
                                </Table.Cell>
                                <Table.Cell class="font-medium">
                                    {item.currency_name}
                                </Table.Cell>
                                <Table.Cell class="text-sm text-muted-foreground">
                                    {item.country_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>
            {#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>
