<script lang="ts">
    import * as Sheet from '$lib/components/ui/sheet';
    import * as Tabs from '$lib/components/ui/tabs';
    import * as Select from '$lib/components/ui/select';
    import * as Dialog from '$lib/components/ui/dialog';
    import { Button } from '$lib/components/ui/button';
    import { Input } from '$lib/components/ui/input';
    import { Label } from '$lib/components/ui/label';
    import { RadioGroup, RadioGroupItem } from '$lib/components/ui/radio-group';
    import { Separator } from '$lib/components/ui/separator';
    import { Loader2, Package, Save, X, FileText, Folder } from 'lucide-svelte';
    import type { Invoice } from '$lib/api/dashboard/a76/invoices';
    import { invoicesApi } from '$lib/api/dashboard/a76/invoices';
    import { itemsApi, type Item, type ImportLineWithBalance } from '$lib/api/dashboard/a76/items';
    import { companyStore } from '$lib/stores/company.svelte';
    
    // Child components
    import InvoiceSelectorModal from '../../InvoiceSelectorModal.svelte';
    import MainData from './main-data.svelte';
    import ItemConfiguration from './item-configuration.svelte';
    import PackagesSection from './packages-section.svelte';
    import SummarySection from './summary-section.svelte';
    import TabContinuation from './tab-continuation.svelte';
    import TabSeries from './tab-series.svelte';
    import TabLabeling from './tab-labeling.svelte';
    import TabIdentifiers from './tab-identifiers.svelte';
	import { getVisibility } from '$lib/config/invoice-item-visibility';

    let { 
        open = $bindable(),
        isEditMode = false,
        editingItem = $bindable(),
        invoice,
		invoiceType = undefined,
		operationType = undefined,
        onSave,
        onCancel,
        isTargetingPreset = false,
        isSaving = false
    }: { 
        open: boolean;
        isEditMode?: boolean;
        editingItem: Partial<Item>;
        invoice: Invoice | null;
		invoiceType?: string | null;
		operationType?: string | number | null;
        onSave: () => void;
        onCancel?: () => void;
        isTargetingPreset?: boolean;
        isSaving?: boolean;
    } = $props();

    // Acceso directo a la primera línea para evitar repeticiones en el HTML
    let line = $derived(editingItem);

    // Ensure series is always an array when sheet is open
    $effect(() => {
        if (open && editingItem) {
            if (!Array.isArray(editingItem.series)) {
                editingItem.series = editingItem.series != null ? [editingItem.series] : [];
            }
            if (!editingItem.fa_data) {
                editingItem.fa_data = {};
            }
            if (editingItem.fa_data.own_equipment === undefined) {
                editingItem.fa_data.own_equipment = false;
            }
            if (editingItem.fa_data.omit_annex31 === undefined) {
                editingItem.fa_data.omit_annex31 = false;
            }
            if (editingItem.fa_data.discharge === undefined) {
                editingItem.fa_data.discharge = true;
            }
        }
    });

    // Selectores de factura (FK): estado y líneas
    let showImportInvoiceModal = $state(false);
    let showExportInvoiceModal = $state(false);
    let showExportLinePicker = $state(false);
    let showImportLinePicker = $state(false);
    let selectedImportInvoiceId = $state<number | null>(null);
    let selectedExportInvoiceId = $state<number | null>(null);
    let importInvoiceLines = $state<ImportLineWithBalance[]>([]);
    let exportInvoiceLines = $state<Item[]>([]);
    let loadingImportLines = $state(false);
    let loadingExportLines = $state(false);

    async function loadImportLines(invoiceId: number) {
        const companyId = companyStore?.activeCompany?.id;
        if (!companyId) return;
        loadingImportLines = true;
        try {
            // Pass the export invoice date so consumption movements after that
            // date are not subtracted from the available balance.
            const asOfDate = invoice?.invoice_date
                ? invoice.invoice_date.split('T')[0]
                : undefined;
            const res = await itemsApi.listByInvoiceWithBalance(invoiceId, companyId, asOfDate);
            importInvoiceLines = res.data ?? [];
        } catch {
            importInvoiceLines = [];
        } finally {
            loadingImportLines = false;
        }
    }

    async function loadExportLines(invoiceId: number) {
        const companyId = companyStore?.activeCompany?.id;
        if (!companyId) return;
        loadingExportLines = true;
        try {
            const res = await itemsApi.listByInvoice(invoiceId, companyId);
            exportInvoiceLines = res.data?.items ?? [];
        } catch {
            exportInvoiceLines = [];
        } finally {
            loadingExportLines = false;
        }
    }

    function handleSelectImportInvoice(inv: Invoice) {
        editingItem.fa_data = editingItem.fa_data || {};
        editingItem.fa_data.search_invoice = inv.invoice_number ?? '';
        editingItem.fa_data.movement_type_import = (inv.invoice_type as string) || 'TEM';
        editingItem.fa_data.search_line = undefined;
        selectedImportInvoiceId = inv.id ?? null;
        if (selectedImportInvoiceId) loadImportLines(selectedImportInvoiceId);
    }

    function handleSelectExportInvoice(inv: Invoice) {
        editingItem.fa_data = editingItem.fa_data || {};
        editingItem.fa_data.search_invoice = inv.invoice_number ?? '';
        editingItem.fa_data.search_line = undefined;
        selectedExportInvoiceId = inv.id ?? null;
        if (selectedExportInvoiceId) loadExportLines(selectedExportInvoiceId);
    }

    const visibility = $derived.by(() => getVisibility(invoiceType ?? invoice?.invoice_type, operationType ?? invoice?.operation_type));
    /** Show link-to-import block for import (CR tracking) or for export when showExportLinkToImportBlock. */
    const showLinkToImportBlock = $derived.by(() => {
        const normalizedOperationType = operationType ?? invoice?.operation_type;
        if (normalizedOperationType === 1 || normalizedOperationType === 'exp') {
            return visibility.showExportLinkToImportBlock;
        }
        return visibility.showCrTrackingHeader;
    });
    /** Show repair-import block (Factura de Expo / Línea de Expo) for REP/REPAR. */
    const showRepairBlock = $derived.by(() => {
        const op = operationType ?? invoice?.operation_type;
        if (op === 1 || op === 'exp') return false;
        return visibility.showRepairLinkToExportBlock;
    });

    // Resolver invoice id desde search_invoice al abrir el sheet (para cargar líneas)
    $effect(() => {
        if (!open || !companyStore?.activeCompany?.id || !editingItem?.fa_data) return;
        const num = editingItem.fa_data.search_invoice;
        const movementType = editingItem.fa_data.movement_type_import;
        if (showLinkToImportBlock && num && !selectedImportInvoiceId && !loadingImportLines) {
            (async () => {
                try {
                    const res = await invoicesApi.list(companyStore.activeCompany!.id, 1, 5, {
                        operation_type: 'imp',
                        invoice_number: num,
                        invoice_type: movementType === 'DEF' ? 'DEF' : 'TEM'
                    });
                    const items = res.data?.items ?? [];
                    const inv = items.find((i: Invoice) => i.invoice_number === num);
                    if (inv?.id) {
                        selectedImportInvoiceId = inv.id;
                        await loadImportLines(inv.id);
                    }
                } catch {
                    // ignore
                }
            })();
        }
        if (showRepairBlock && num && !selectedExportInvoiceId && !loadingExportLines) {
            (async () => {
                try {
                    const res = await invoicesApi.list(companyStore.activeCompany!.id, 1, 5, {
                        operation_type: 'exp',
                        invoice_number: num
                    });
                    const items = res.data?.items ?? [];
                    const inv = items.find((i: Invoice) => i.invoice_number === num);
                    if (inv?.id) {
                        selectedExportInvoiceId = inv.id;
                        await loadExportLines(inv.id);
                    }
                } catch {
                    // ignore
                }
            })();
        }
    });

    $effect(() => {
        if (!open) {
            selectedImportInvoiceId = null;
            selectedExportInvoiceId = null;
            importInvoiceLines = [];
            exportInvoiceLines = [];
        }
    });

    const importRegimenLabel = $derived(
        (editingItem.fa_data?.movement_type_import?.toUpperCase() === 'DEF' ? 'Definitiva' : 'Temporal')
    );

    const showCrTrackingBlock = $derived.by(() => {
        const normalizedOperationType = operationType ?? invoice?.operation_type;
        if (normalizedOperationType === 1 || normalizedOperationType === 'exp') {
            return false;
        }
        return visibility.showCrTrackingHeader;
    });
    const isExport = $derived.by(() => {
        const op = operationType ?? invoice?.operation_type;
        return op === 1 || op === 'exp';
    });
    const visibleTabs = $derived.by(() => [
        { value: 'generales', label: 'General', visible: true },
        { value: 'continuacion', label: 'Continuación', visible: true },
        { value: 'series', label: 'Series', visible: true },
        { value: 'etiquetado', label: 'Etiquetado', visible: visibility.showLabelingTab },
        { value: 'identificadores', label: 'IDs', visible: visibility.showIdentifiersTab }
    ].filter((tab) => tab.visible));
    const tabListStyle = $derived(`grid-template-columns: repeat(${visibleTabs.length || 1}, minmax(0, 1fr));`);
    let activeTab = $state('generales');

    $effect(() => {
        if (!visibleTabs.some((tab) => tab.value === activeTab)) {
            activeTab = visibleTabs[0]?.value || 'generales';
        }
    });
</script>

<Sheet.Root bind:open={open}>
    <Sheet.Content side="right" class="w-full sm:max-w-[95vw] lg:max-w-[85vw] xl:max-w-[75vw] p-0 flex flex-col h-full bg-slate-50 dark:bg-black">
        
        <header class="bg-white dark:bg-zinc-950 border-b dark:border-zinc-800 px-3 py-1.5 shadow-sm shrink-0">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-2">
                    <div class="bg-zinc-900 p-1 rounded">
                        <Package class="w-3.5 h-3.5 text-white" />
                    </div>
                    <div>
                        <Sheet.Title class="text-sm font-semibold text-zinc-900 dark:text-zinc-100 leading-tight">
                            {isEditMode ? 'Editar Partida' : 'Nueva Partida - Activo Fijo'}
                        </Sheet.Title>
                        <p class="text-[10px] text-muted-foreground flex items-center gap-1.5">
                            Factura: <span class="font-medium text-zinc-700 dark:text-zinc-300">{invoice?.invoice_number || 'N/A'}</span>
                        </p>
                    </div>
                </div>
                <Button variant="ghost" size="icon" onclick={() => onCancel?.()} class="h-7 w-7 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800">
                    <X class="w-3.5 h-3.5" />
                </Button>
            </div>
        </header>

        <div class="flex-1 overflow-y-auto px-2">
            <div class="space-y-2">
                
                {#if line}
                    {#if showRepairBlock}
                        <!-- Importación de Reparación: Genera Descarga? + Factura de Expo + Línea de Expo -->
                        <div class="space-y-3 rounded-md border border-zinc-200 bg-white p-3 dark:border-zinc-800 dark:bg-zinc-900">
                            <div class="space-y-1.5">
                                <Label class="text-xs font-medium text-muted-foreground">Genera Descarga?</Label>
                                <RadioGroup
                                    value={editingItem.fa_data?.discharge === false ? 'no' : 'si'}
                                    onValueChange={(v) => {
                                        editingItem.fa_data = editingItem.fa_data || {};
                                        editingItem.fa_data.discharge = v === 'si';
                                    }}
                                    class="flex gap-4"
                                >
                                    <div class="flex items-center gap-2">
                                        <RadioGroupItem value="si" id="fa_rep_download_si" />
                                        <Label for="fa_rep_download_si" class="text-xs cursor-pointer">Sí</Label>
                                    </div>
                                    <div class="flex items-center gap-2">
                                        <RadioGroupItem value="no" id="fa_rep_download_no" />
                                        <Label for="fa_rep_download_no" class="text-xs cursor-pointer">No</Label>
                                    </div>
                                </RadioGroup>
                            </div>
                            <!-- Fila ligada: selector de factura (FK) + línea (FK), estilo Input + Folder -->
                            <div class="flex flex-wrap items-end gap-3">
                                <div class="min-w-[120px] flex-1 space-y-1">
                                    <Label class="text-xs">Factura de Expo</Label>
                                    <div class="flex gap-1">
                                        <Input
                                            readonly
                                            value={editingItem.fa_data?.search_invoice || ''}
                                            class="h-8 flex-1 bg-muted cursor-pointer text-sm"
                                            placeholder="Seleccionar factura..."
                                            onclick={() => (showExportInvoiceModal = true)}
                                        />
                                        <Button
                                            type="button"
                                            variant="outline"
                                            size="icon"
                                            class="h-8 w-8 shrink-0"
                                            onclick={() => (showExportInvoiceModal = true)}
                                        >
                                            <Folder class="h-4 w-4" />
                                        </Button>
                                    </div>
                                </div>
                                <div class="min-w-[90px] flex-1 space-y-1">
                                    <Label for="fa_rep_search_line" class="text-xs">Línea de Expo</Label>
                                    <div class="flex gap-1">
                                        <Input
                                            id="fa_rep_search_line"
                                            readonly
                                            value={editingItem.fa_data?.search_line != null ? String(editingItem.fa_data.search_line) : ''}
                                            class="h-8 flex-1 bg-muted cursor-pointer text-sm"
                                            placeholder={loadingExportLines ? 'Cargando...' : 'Línea'}
                                            disabled={!selectedExportInvoiceId || loadingExportLines}
                                            onclick={() => selectedExportInvoiceId && !loadingExportLines && (showExportLinePicker = true)}
                                        />
                                        <Button
                                            type="button"
                                            variant="outline"
                                            size="icon"
                                            class="h-8 w-8 shrink-0"
                                            disabled={!selectedExportInvoiceId || loadingExportLines}
                                            onclick={() => (showExportLinePicker = true)}
                                        >
                                            <Folder class="h-4 w-4" />
                                        </Button>
                                    </div>
                                </div>
                                <div class="min-w-[100px] flex-1 space-y-1">
                                    <Label for="fa_rep_search_type" class="text-xs">Tipo Búsqueda</Label>
                                    <Select.Root
                                        type="single"
                                        value={editingItem.fa_data?.search_type || ''}
                                        onValueChange={(v) => {
                                            editingItem.fa_data = editingItem.fa_data || {};
                                            editingItem.fa_data.search_type = v ?? 'Factura';
                                        }}
                                    >
                                        <Select.Trigger id="fa_rep_search_type" class="h-8 text-sm">
                                            <span class="truncate">
                                                {editingItem.fa_data?.search_type || 'Seleccionar...'}
                                            </span>
                                        </Select.Trigger>
                                        <Select.Content>
                                            <Select.Item value="Factura">Factura</Select.Item>
                                            <Select.Item value="NumParte">NumParte</Select.Item>
                                            <Select.Item value="Clase">Clase</Select.Item>
                                        </Select.Content>
                                    </Select.Root>
                                </div>
                            </div>
                        </div>
                    {:else if showLinkToImportBlock}
                        <div class="space-y-3 rounded-md border border-zinc-200 bg-white p-3 dark:border-zinc-800 dark:bg-zinc-900">
                            <div class="space-y-1.5">
                                <Label class="text-xs font-medium text-muted-foreground">Genera Descarga?</Label>
                                <RadioGroup
                                    value={editingItem.fa_data?.discharge === false ? 'no' : 'si'}
                                    onValueChange={(v) => {
                                        editingItem.fa_data = editingItem.fa_data || {};
                                        editingItem.fa_data.discharge = v === 'si';
                                    }}
                                    class="flex gap-4"
                                >
                                    <div class="flex items-center gap-2">
                                        <RadioGroupItem value="si" id="fa_download_si" />
                                        <Label for="fa_download_si" class="text-xs cursor-pointer">Sí</Label>
                                    </div>
                                    <div class="flex items-center gap-2">
                                        <RadioGroupItem value="no" id="fa_download_no" />
                                        <Label for="fa_download_no" class="text-xs cursor-pointer">No</Label>
                                    </div>
                                </RadioGroup>
                            </div>
                            <!-- Fila ligada: selector de factura (FK) + línea (FK) -->
                            <div class="flex flex-wrap items-end gap-3">
                                <div class="min-w-[100px] flex-1 space-y-1">
                                    <Label class="text-xs">Tipo Importación</Label>
                                    <Select.Root
                                        type="single"
                                        value={editingItem.fa_data?.movement_type_import || 'TEM'}
                                        onValueChange={(v) => {
                                            editingItem.fa_data = editingItem.fa_data || {};
                                            editingItem.fa_data.movement_type_import = v || 'TEM';
                                            selectedImportInvoiceId = null;
                                            importInvoiceLines = [];
                                        }}
                                    >
                                        <Select.Trigger class="h-8 text-sm">
                                            <span>{editingItem.fa_data?.movement_type_import === 'DEF' ? 'DEF' : 'TEM'}</span>
                                        </Select.Trigger>
                                        <Select.Content>
                                            <Select.Item value="TEM">TEM (Temporal)</Select.Item>
                                            <Select.Item value="DEF">DEF (Definitiva)</Select.Item>
                                        </Select.Content>
                                    </Select.Root>
                                </div>
                                <div class="min-w-[120px] flex-1 space-y-1">
                                    <Label class="text-xs">Factura Impo</Label>
                                    <div class="flex gap-1">
                                        <Input
                                            readonly
                                            value={editingItem.fa_data?.search_invoice || ''}
                                            class="h-8 flex-1 bg-muted cursor-pointer text-sm"
                                            placeholder="Seleccionar factura..."
                                            onclick={() => (showImportInvoiceModal = true)}
                                        />
                                        <Button
                                            type="button"
                                            variant="outline"
                                            size="icon"
                                            class="h-8 w-8 shrink-0"
                                            onclick={() => (showImportInvoiceModal = true)}
                                        >
                                            <Folder class="h-4 w-4" />
                                        </Button>
                                    </div>
                                </div>
                                <div class="min-w-[90px] flex-1 space-y-1">
                                    <Label for="fa_search_line" class="text-xs">Línea</Label>
                                    <div class="flex gap-1">
                                        <Input
                                            id="fa_search_line"
                                            readonly
                                            value={editingItem.fa_data?.search_line != null ? String(editingItem.fa_data.search_line) : ''}
                                            class="h-8 flex-1 bg-muted cursor-pointer text-sm"
                                            placeholder={loadingImportLines ? 'Cargando...' : 'Línea'}
                                            disabled={!selectedImportInvoiceId || loadingImportLines}
                                            onclick={() => selectedImportInvoiceId && !loadingImportLines && (showImportLinePicker = true)}
                                        />
                                        <Button
                                            type="button"
                                            variant="outline"
                                            size="icon"
                                            class="h-8 w-8 shrink-0"
                                            disabled={!selectedImportInvoiceId || loadingImportLines}
                                            onclick={() => (showImportLinePicker = true)}
                                        >
                                            <Folder class="h-4 w-4" />
                                        </Button>
                                    </div>
                                </div>
                                <div class="min-w-[100px] flex-1 space-y-1">
                                    <Label for="fa_search_type" class="text-xs">Tipo Búsqueda</Label>
                                    <Select.Root
                                        type="single"
                                        value={editingItem.fa_data?.search_type || ''}
                                        onValueChange={(v) => {
                                            editingItem.fa_data = editingItem.fa_data || {};
                                            editingItem.fa_data.search_type = v ?? undefined;
                                        }}
                                    >
                                        <Select.Trigger id="fa_search_type" class="h-8 text-sm">
                                            <span class="truncate">
                                                {editingItem.fa_data?.search_type || 'Seleccionar...'}
                                            </span>
                                        </Select.Trigger>
                                        <Select.Content>
                                            <Select.Item value="Factura">Factura</Select.Item>
                                            <Select.Item value="NumParte">NumParte</Select.Item>
                                        </Select.Content>
                                    </Select.Root>
                                </div>
                            </div>
                        </div>
                    {/if}

                    <div class="grid grid-cols-1 lg:grid-cols-12 gap-2">
                        <div class="lg:col-span-8">
                            <div class="bg-white dark:bg-zinc-900 rounded border border-zinc-200 dark:border-zinc-800 overflow-hidden">
                                <div class="bg-zinc-50 dark:bg-zinc-800/50 px-2 py-1 border-b border-zinc-200 dark:border-zinc-800">
                                    <h3 class="text-[10px] font-semibold text-zinc-500 uppercase tracking-wide">Datos Principales</h3>
                                </div>
                                <div class="p-2">
                                    <MainData 
                                        bind:lineItem={editingItem}
                                        bind:quantities={editingItem.quantity!}
                                        bind:financials={editingItem.financial!}
                                        bind:customs={editingItem.customs!}
                                        {invoice}
                                    />
                                </div>
                            </div>
                        </div>

                        <div class="lg:col-span-4">
                            <div class="bg-white dark:bg-zinc-900 rounded border border-zinc-200 dark:border-zinc-800 h-full overflow-hidden">
                                <div class="bg-zinc-50 dark:bg-zinc-800/50 px-2 py-1 border-b border-zinc-200 dark:border-zinc-800">
                                    <h3 class="text-[10px] font-semibold text-zinc-500 uppercase tracking-wide">Configuración</h3>
                                </div>
                                <div class="p-2">
                                    <ItemConfiguration 
                                        bind:lineItem={editingItem}
                                        bind:descriptions={editingItem.description!}
                                    />
                                </div>
                            </div>
                        </div>
                    </div>

                    <Tabs.Root bind:value={activeTab} class="w-full">
                        <Tabs.List class="grid w-full gap-0.5 rounded bg-zinc-100 p-0.5 dark:bg-zinc-800/50" style={tabListStyle}>
                            {#each visibleTabs as tab}
                                <Tabs.Trigger value={tab.value} class="text-xs font-medium py-1.5 px-2 rounded transition-all data-[state=active]:bg-white dark:data-[state=active]:bg-zinc-700 data-[state=active]:shadow-sm data-[state=active]:text-black dark:data-[state=active]:text-white">
                                    {tab.label}
                                </Tabs.Trigger>
                            {/each}
                        </Tabs.List>

                        <div class="mt-1.5">
                            <Tabs.Content value="generales" class="m-0">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
                                    <PackagesSection 
                                        bind:item={editingItem}
                                        bind:lineItem={editingItem}
                                        bind:descriptions={editingItem.description!}
                                        bind:customs={editingItem.customs!}
                                        bind:quantities={editingItem.quantity!}
                                        invoice={invoice}
                                    />
                                    <SummarySection 
                                        bind:financials={editingItem.financial!}
                                        bind:quantities={editingItem.quantity!}
                                        lineItem={editingItem}
                                        {invoice}
                                    />
                                </div>
                            </Tabs.Content>

                            <Tabs.Content value="continuacion" class="m-0 focus-visible:outline-none">
                                <TabContinuation 
                                    bind:lineItem={editingItem}
                                    bind:descriptions={editingItem.description!}
									visibility={visibility}
                                />
                            </Tabs.Content>

                            <Tabs.Content value="series" class="m-0 focus-visible:outline-none">
                                <TabSeries
                                    bind:descriptions={editingItem.description!}
                                    bind:series={editingItem.series!}
                                    lineItem={editingItem}
                                    {invoice}
                                />
                            </Tabs.Content>

                            {#if visibility.showLabelingTab}
                                <Tabs.Content value="etiquetado" class="m-0 focus-visible:outline-none">
                                    <TabLabeling bind:lineItem={editingItem} bind:descriptions={editingItem.description!} {visibility} />
                                </Tabs.Content>
                            {/if}

                            {#if visibility.showIdentifiersTab}
                                <Tabs.Content value="identificadores" class="m-0 focus-visible:outline-none">
                                    <TabIdentifiers 
                                        bind:lineItem={editingItem} 
                                        invoiceConsecutive={invoice?.id}
                                        invoiceNumber={invoice?.invoice_number ?? ''}
                                        {visibility}
                                    />
                                </Tabs.Content>
                            {/if}
                        </div>
                    </Tabs.Root>
                {:else}
                    <div class="flex flex-col items-center justify-center py-20 text-muted-foreground">
                        <Loader2 class="w-8 h-8 animate-spin mb-4 text-zinc-900 dark:text-zinc-100" />
                        <p class="text-sm">Cargando datos de la partida...</p>
                    </div>
                {/if}
            </div>
        </div>

        <footer class="bg-white dark:bg-zinc-950 border-t border-zinc-200 dark:border-zinc-800 px-3 py-1.5 shadow-sm shrink-0">
            <div class="flex items-center justify-end gap-1.5">
                <Button variant="outline" size="sm" onclick={() => onCancel?.()} disabled={isSaving} class="h-7 text-xs px-2">
                    Cancelar
                </Button>
                <Button size="sm" onclick={onSave} disabled={isSaving} class="h-7 text-xs px-2 bg-blue-600 hover:bg-blue-700 dark:bg-blue-600 dark:hover:bg-blue-700 text-white">
                    {#if isSaving}
                        <Loader2 class="w-3 h-3 mr-1 animate-spin" />
                        Guardando...
                    {:else}
                        <Save class="w-3 h-3 mr-1" />
                        {isEditMode ? 'Actualizar' : 'Crear'}
                    {/if}
                </Button>
            </div>
        </footer>

    </Sheet.Content>
</Sheet.Root>

<InvoiceSelectorModal
    bind:open={showImportInvoiceModal}
    regimen={importRegimenLabel}
    operationType="imp"
    onSelect={handleSelectImportInvoice}
/>
<InvoiceSelectorModal
    bind:open={showExportInvoiceModal}
    operationType="exp"
    onSelect={handleSelectExportInvoice}
/>

<!-- Diálogo para elegir línea (Expo) -->
<Dialog.Root bind:open={showExportLinePicker}>
    <Dialog.Content class="max-w-sm">
        <Dialog.Header>
            <Dialog.Title class="text-sm">Seleccionar línea</Dialog.Title>
        </Dialog.Header>
        <div class="max-h-[280px] overflow-y-auto py-2">
            {#each exportInvoiceLines as lineItem}
                {@const num = lineItem.line_number ?? lineItem.id}
                <button
                    type="button"
                    class="w-full px-3 py-2 text-left text-sm hover:bg-muted rounded-md"
                    onclick={() => {
                        editingItem.fa_data = editingItem.fa_data || {};
                        editingItem.fa_data.search_line = typeof num === 'number' ? num : undefined;
                        showExportLinePicker = false;
                    }}
                >
                    Línea {num}
                </button>
            {/each}
        </div>
    </Dialog.Content>
</Dialog.Root>

<!-- Diálogo para elegir línea (Impo) -->
<Dialog.Root bind:open={showImportLinePicker}>
    <Dialog.Content class="max-w-4xl">
        <Dialog.Header>
            <Dialog.Title class="text-sm">Seleccionar línea de importación</Dialog.Title>
            <p class="text-xs text-muted-foreground mt-0.5">
                Solo se muestran líneas con saldo disponible
            </p>
        </Dialog.Header>
        <!-- overflow-x on a wrapper that does NOT also do overflow-y.
             The inner div handles vertical scroll so sticky columns work
             independently from the horizontal scrollbar. -->
        <div class="overflow-x-auto">
            <div class="overflow-y-auto max-h-[500px]">
            {#if importInvoiceLines.every(l => !l.has_balance)}
                <p class="px-3 py-8 text-xs text-muted-foreground text-center">
                    No hay líneas con saldo disponible en esta factura.
                </p>
            {:else}
                <table class="text-xs border-collapse" style="min-width: max-content; width: 100%;">
                    <thead class="sticky top-0 z-20">
                        <tr class="border-b border-border bg-muted">
                            <!-- sticky cols 1-3: left offsets match td widths below -->
                            <th class="sticky left-0 z-20 bg-muted px-2 py-2 text-left font-semibold text-muted-foreground whitespace-nowrap w-[48px]">Línea</th>
                            <th class="sticky left-[48px] z-20 bg-muted px-2 py-2 text-left font-semibold text-muted-foreground whitespace-nowrap w-[120px]">Factura</th>
                            <th class="sticky left-[168px] z-20 bg-muted px-2 py-2 text-left font-semibold text-muted-foreground whitespace-nowrap w-[88px]">Fecha</th>
                            <th class="px-2 py-2 text-left font-semibold text-muted-foreground whitespace-nowrap">Num. Parte</th>
                            <th class="px-2 py-2 text-left font-semibold text-muted-foreground whitespace-nowrap">Clase</th>
                            <th class="px-2 py-2 text-left font-semibold text-muted-foreground whitespace-nowrap w-[180px]">Descripción</th>
                            <th class="px-2 py-2 text-right font-semibold text-muted-foreground whitespace-nowrap">Cant. Imp.</th>
                            <th class="px-2 py-2 text-right font-semibold text-muted-foreground whitespace-nowrap">Ret. Temp.</th>
                            <th class="px-2 py-2 text-right font-semibold text-muted-foreground whitespace-nowrap">Ret. Def.</th>
                            <th class="px-2 py-2 text-right font-semibold text-muted-foreground whitespace-nowrap">Saldo Disp.</th>
                            <th class="px-2 py-2 text-center font-semibold text-muted-foreground whitespace-nowrap">Estatus</th>
                            <th class="px-2 py-2 text-center font-semibold text-muted-foreground whitespace-nowrap">Sub.</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-border">
                        {#each importInvoiceLines as lineItem}
                            {#if lineItem.has_balance}
                                <tr
                                    class="hover:bg-muted/50 cursor-pointer transition-colors group"
                                    onclick={() => {
                                        editingItem.fa_data = editingItem.fa_data || {};
                                        editingItem.fa_data.search_line = lineItem.line_number;
                                        showImportLinePicker = false;
                                    }}
                                >
                                    <td class="sticky left-0 z-10 bg-background group-hover:bg-muted/50 px-2 py-1.5 font-semibold text-primary whitespace-nowrap w-[48px]">{lineItem.line_number}</td>
                                    <td class="sticky left-[48px] z-10 bg-background group-hover:bg-muted/50 px-2 py-1.5 font-mono whitespace-nowrap w-[120px]">{lineItem.invoice_number ?? '-'}</td>
                                    <td class="sticky left-[168px] z-10 bg-background group-hover:bg-muted/50 px-2 py-1.5 text-muted-foreground whitespace-nowrap w-[88px]">
                                        {lineItem.invoice_date ? lineItem.invoice_date.slice(0, 10) : '-'}
                                    </td>
                                    <td class="px-2 py-1.5 font-mono whitespace-nowrap">{lineItem.part_number ?? '-'}</td>
                                    <td class="px-2 py-1.5 whitespace-nowrap">{lineItem.class_code ?? '-'}</td>
                                    <td class="px-2 py-1.5 w-[180px] max-w-[180px] truncate text-muted-foreground" title={lineItem.description_spanish ?? ''}>
                                        {lineItem.description_spanish ?? '-'}
                                    </td>
                                    <td class="px-2 py-1.5 text-right tabular-nums whitespace-nowrap">
                                        {lineItem.quantity != null ? lineItem.quantity.toLocaleString('es-MX', { maximumFractionDigits: 4 }) : '-'}
                                        <span class="text-muted-foreground">{lineItem.unit_of_measure_code ?? ''}</span>
                                    </td>
                                    <td class="px-2 py-1.5 text-right tabular-nums whitespace-nowrap text-amber-600 dark:text-amber-400">
                                        {lineItem.quantity_returned_temp != null ? lineItem.quantity_returned_temp.toLocaleString('es-MX', { maximumFractionDigits: 4 }) : '-'}
                                    </td>
                                    <td class="px-2 py-1.5 text-right tabular-nums whitespace-nowrap text-blue-600 dark:text-blue-400">
                                        {lineItem.quantity_returned != null ? lineItem.quantity_returned.toLocaleString('es-MX', { maximumFractionDigits: 4 }) : '-'}
                                    </td>
                                    <td class="px-2 py-1.5 text-right tabular-nums font-semibold whitespace-nowrap text-emerald-600 dark:text-emerald-400">
                                        {lineItem.available_balance.toLocaleString('es-MX', { maximumFractionDigits: 4 })}
                                        <span class="font-normal text-muted-foreground">{lineItem.unit_of_measure_code ?? ''}</span>
                                    </td>
                                    <td class="px-2 py-1.5 text-center whitespace-nowrap">
                                        {#if lineItem.invoice_status === 'processed'}
                                            <span class="inline-flex items-center rounded-full bg-emerald-100 dark:bg-emerald-900/40 px-1.5 py-0.5 text-[10px] font-medium text-emerald-700 dark:text-emerald-300">
                                                Procesada
                                            </span>
                                        {:else if lineItem.invoice_status === 'reversed'}
                                            <span class="inline-flex items-center rounded-full bg-red-100 dark:bg-red-900/40 px-1.5 py-0.5 text-[10px] font-medium text-red-700 dark:text-red-300">
                                                Revertida
                                            </span>
                                        {:else}
                                            <span class="inline-flex items-center rounded-full bg-zinc-100 dark:bg-zinc-800 px-1.5 py-0.5 text-[10px] font-medium text-zinc-600 dark:text-zinc-400">
                                                {lineItem.invoice_status ?? 'Pendiente'}
                                            </span>
                                        {/if}
                                    </td>
                                    <td class="px-2 py-1.5 text-center whitespace-nowrap">
                                        {#if lineItem.is_subitem}
                                            <span class="inline-flex items-center rounded-full bg-purple-100 dark:bg-purple-900/40 px-1.5 py-0.5 text-[10px] font-medium text-purple-700 dark:text-purple-300">
                                                Sub
                                            </span>
                                        {:else if lineItem.contains_subitems}
                                            <span class="inline-flex items-center rounded-full bg-indigo-100 dark:bg-indigo-900/40 px-1.5 py-0.5 text-[10px] font-medium text-indigo-700 dark:text-indigo-300" title="{lineItem.subitem_count} subpartida(s)">
                                                {lineItem.subitem_count ?? 0} sub
                                            </span>
                                        {:else}
                                            <span class="text-muted-foreground">—</span>
                                        {/if}
                                    </td>
                                </tr>
                            {/if}
                        {/each}
                    </tbody>
                </table>
            {/if}
            </div>
        </div>
    </Dialog.Content>
</Dialog.Root>