<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 type { TariffFraction } from "$lib/api/dashboard/a76/general_catalogs/tariff-fractions";
    import { getUSTariffFractions } from "$lib/api/dashboard/a76/general_catalogs/us-tariff-fractions";
    import { getTariffFractionDisplayKey } from '$lib/utils/tariff-fraction-display';
    import { companyStore } from "$lib/stores/company.svelte";
    import { m } from '$lib/i18n/messages';

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

    // --- ESTADO ---
    let items = $state<TariffFraction[]>([]);
    let loading = $state(false);
    let searchTerm = $state("");
    let loadedForCompanyId = $state<number | null>(null);

    const activeCompanyId = $derived(companyStore.activeCompany?.id);

    function normalizeAmericanFractionCode(code: string) {
        return (code || '').replace(/[.\s-]/g, '');
    }

    function isEligibleAmericanFraction(item: TariffFraction) {
        const normalizedCode = normalizeAmericanFractionCode(item.code || item.fraction || '');
        return /^\d{8}$/.test(normalizedCode) || /^\d{10}$/.test(normalizedCode);
    }

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

    // Cargar datos al abrir
    $effect(() => {
        if (!open) return;

        if (!activeCompanyId) {
            items = [];
            loadedForCompanyId = null;
            return;
        }

        if (loadedForCompanyId !== activeCompanyId) {
            searchTerm = '';
            items = [];
            void loadFractions(activeCompanyId);
        }
    });

    function mapUsFractionToTariffFraction(item: any): TariffFraction {
        return {
            id: item.id,
            code: item.code || '',
            fraction: item.fraction || item.code || '',
            description: item.description || '',
            nico: null,
            umt: item.unit_of_measure || null,
            adv_impo: item.ad_valorem != null ? String(item.ad_valorem) : null,
            adv_expo: null
        };
    }

    async function loadFractions(companyId: number) {
        if (!companyId) {
            toast.error(m.invoice_selectors_us_tariff_fraction_no_company_selected());
            return;
        }
        
        loading = true;
        try {
            const response = await getUSTariffFractions(1, 1000, companyId);
            
            if (response.error) {
                console.error("Error al cargar fracciones americanas:", response.error);
                toast.error(m.invoice_selectors_us_tariff_fraction_load_error_prefix({ error: String(response.error) }));
                return;
            }

            if (response.data?.items) {
                items = response.data.items
                    .map(mapUsFractionToTariffFraction)
                    .filter((item) => isEligibleAmericanFraction(item));
                loadedForCompanyId = companyId;
            } else {
                console.warn("No se encontraron fracciones americanas:", response);
                toast.info(m.invoice_selectors_us_tariff_fraction_no_records_info());
            }
        } catch (e: any) {
            console.error("Excepción cargando fracciones americanas:", e);
            toast.error(
                m.invoice_selectors_us_tariff_fraction_connection_error_prefix({
                    error: String(e?.message || e)
                })
            );
        } finally {
            loading = false;
        }
    }

    function handleSelect(item: TariffFraction) {
        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 z-[300]">
        <Dialog.Header>
            <Dialog.Title>{m.invoice_selectors_us_tariff_fraction_title()}</Dialog.Title>
            <Dialog.Description>
                {m.invoice_selectors_us_tariff_fraction_description()}
            </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={m.invoice_selectors_us_tariff_fraction_search_placeholder()} 
                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>{m.invoice_selectors_us_tariff_fraction_loading_catalog()}</p>
                </div>
            {:else if filteredItems.length === 0}
                <div class="flex flex-col items-center justify-center h-48 text-muted-foreground">
                    <p>{m.invoice_selectors_us_tariff_fraction_no_results()}</p>
                </div>
            {:else}
                <Table.Root>
                    <Table.Header>
                        <Table.Row>
                            <Table.Head class="w-[150px]">{m.invoice_selectors_us_tariff_fraction_column_code()}</Table.Head>
                            <Table.Head>{m.invoice_selectors_us_tariff_fraction_column_description()}</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">
                                            {getTariffFractionDisplayKey(item)}
                                        </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">
                {m.invoice_selectors_us_tariff_fraction_records_found({ count: String(filteredItems.length) })}
            </div>
            {#if onClear}
                <Button variant="ghost" onclick={() => { onClear(); open = false; }}>Quitar selección</Button>
            {/if}
            <Button variant="outline" onclick={() => open = false}>{m.invoice_selectors_us_tariff_fraction_cancel()}</Button>
        </Dialog.Footer>
    </Dialog.Content>
</Dialog.Root>
