<script lang="ts">
	import { tick } from 'svelte';
	import { browser } from '$app/environment';
    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, Calendar, AlertCircle } 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';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosPestanasItemFa } from '$lib/config/shortcuts/dashboard/invoices/item/fixed_asset';
    import { m } from '$lib/i18n/messages';
    
    // 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,
        saveError = null,
        onDismissSaveError,
        activeTab = $bindable('generales'),
        onValidationFieldChange
    }: { 
        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;
        saveError?: { field: string; message: string }[] | null;
        onDismissSaveError?: () => void;
        activeTab?: string;
        onValidationFieldChange?: (fieldPath: string) => void;
    } = $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 = false;
            }
            if ((editingItem.fa_data.movement_type_import === undefined || editingItem.fa_data.movement_type_import === '') && (showLinkToImportBlock || showRepairBlock)) {
                editingItem.fa_data.movement_type_import = 'TEM';
            }
        }
    });

    // 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 loadingImportDetails = $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, 
                invoice?.id
            );
            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));
    
    // Proportional weight calculation (CALCULO_PESOS)
    function recalculateWeights() {
        if (!editingItem.quantity || !editingItem.fa_data?.discharge) return;
        
        const qty = Number(editingItem.quantity.quantity || 0);
        const sourceQty = Number(editingItem.fa_data.source_quantity || 0);
        const sourceNet = Number(editingItem.fa_data.source_net_weight || 0);
        const sourceGross = Number(editingItem.fa_data.source_gross_weight || 0);
        const sourcePackages = Number(editingItem.fa_data.source_packages || 0);

        if (sourceQty > 0) {
            editingItem.quantity.net_weight = Number((qty * (sourceNet / sourceQty)).toFixed(8));
            editingItem.quantity.gross_weight = Number((qty * (sourceGross / sourceQty)).toFixed(8));
            editingItem.quantity.package_quantity = Math.floor(qty * (sourcePackages / sourceQty));
        }
    }

    // Watch for quantity changes to recalculate proportional weights
    $effect(() => {
        const qty = editingItem.quantity?.quantity;
        if (qty !== undefined && editingItem.fa_data?.discharge) {
            recalculateWeights();
        }
    });

    /** 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 {
                    // Do NOT filter by invoice_type: if movement_type_import is null or
                    // mismatched the invoice won't be found, leaving the line picker
                    // permanently disabled. Exact match is enforced by .find() below.
                    const res = await invoicesApi.list(companyStore.activeCompany!.id, 1, 50, {
                        operation_type: 'imp',
                        invoice_number: num
                    });
                    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, 50, {
                        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 isReadOnly = $derived(invoice?.status === 'processed');

    const isExport = $derived.by(() => {
        const op = operationType ?? invoice?.operation_type;
        return op === 1 || op === 'exp';
    });
    const visibleTabs = $derived.by(() => [
        { value: 'generales', label: m['invoice_item_fa.item_sheet.tab_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: m['invoice_item_fa.item_sheet.tab_identifiers'](), visible: visibility.showIdentifiersTab }
    ].filter((tab) => tab.visible));
    const tabListStyle = $derived(`grid-template-columns: repeat(${visibleTabs.length || 1}, minmax(0, 1fr));`);
    const tabMapping: Record<string, string> = {
        tab1: 'generales',
        tab2: 'continuacion',
        tab3: 'series',
        tab4: 'etiquetado',
        tab5: 'identificadores'
    };

    function openOnEnterOrSpace(event: KeyboardEvent, action: () => void) {
        if (event.key === 'Enter' || event.key === ' ') {
            event.preventDefault();
            action();
        }
    }

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

    useShortcuts(
        'Invoice Item Form (Fixed Asset)',
        obtenerAtajosPestanasItemFa({
            cambiarPestana: (target) => {
                const mappedTab = tabMapping[target];
                if (!mappedTab) return;
                if (visibleTabs.some((tab) => tab.value === mappedTab)) {
                    activeTab = mappedTab;
                }
            },
            manejarGuardar: onSave,
            manejarCancelar: () => onCancel?.()
        })
    );

	let previousSheetOpen = $state(false);
	$effect(() => {
		if (!browser) return;
		if (open && !previousSheetOpen) {
			void tick().then(() => {
				const root = document.querySelector('[data-invoice-item-sheet="fixed_asset"]');
				const first = root?.querySelector<HTMLElement>(
					'input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled])'
				);
				first?.focus();
			});
		}
		previousSheetOpen = open;
	});
</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"
		data-invoice-item-sheet="fixed_asset"
	>
        
        <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 || m['invoice_item_fa.item_sheet.not_available_short']()}</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"
            oninput={(e) => {
                const path = (e.target as HTMLElement).getAttribute('data-item-validation-path');
                if (path) onValidationFieldChange?.(path);
            }}
            onchange={(e) => {
                const path = (e.target as HTMLElement).getAttribute('data-item-validation-path');
                if (path) onValidationFieldChange?.(path);
            }}
        >
            <div class="space-y-2">
                
                {#if editingItem}
                    {#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">{m['invoice_item_fa.repair.generate_discharge']()}</Label>
                                <p class="text-[10px] text-muted-foreground -mt-1">Los campos marcados con * son obligatorios.</p>
                                <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">{m['invoice_item_fa.repair.export_invoice_label']()}</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={m['invoice_item_fa.repair.search_placeholder']()}
                                            onclick={() => (showExportInvoiceModal = true)}
                                            tabindex={0}
                                            onkeydown={(event) =>
                                                openOnEnterOrSpace(event, () => (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">{m['invoice_item_fa.repair.export_line_label']()}</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 ? m['invoice_item_fa.repair.loading_line']() : m['invoice_item_fa.repair.line_label']()}
                                            disabled={!selectedExportInvoiceId || loadingExportLines}
                                            onclick={() => selectedExportInvoiceId && !loadingExportLines && (showExportLinePicker = true)}
                                            tabindex={!selectedExportInvoiceId || loadingExportLines ? -1 : 0}
                                            onkeydown={(event) =>
                                                openOnEnterOrSpace(
                                                    event,
                                                    () =>
                                                        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">{m['invoice_item_fa.repair.type_search_label']()}</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 || m['invoice_item_fa.repair.search_placeholder']()}
                                            </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">{m['invoice_item_fa.repair.generate_discharge']()}</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">{m['invoice_item_fa.repair.import_type_label']()} <span class="text-red-500">*</span></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">{m['invoice_item_fa.repair.temporal']()}</Select.Item>
                                            <Select.Item value="DEF">{m['invoice_item_fa.repair.definitive']()}</Select.Item>
                                        </Select.Content>
                                    </Select.Root>
                                </div>
                                <div class="min-w-[120px] flex-1 space-y-1">
                                    <Label class="text-xs">{m['invoice_item_fa.repair.import_invoice_label']()}</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={m['invoice_item_fa.repair.search_placeholder']()}
                                            onclick={() => (showImportInvoiceModal = true)}
                                            tabindex={0}
                                            onkeydown={(event) =>
                                                openOnEnterOrSpace(event, () => (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">{m['invoice_item_fa.repair.line_label']()}</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 ? m['invoice_item_fa.repair.loading_line']() : m['invoice_item_fa.repair.line_label']()}
                                            disabled={!selectedImportInvoiceId || loadingImportLines}
                                            onclick={() => selectedImportInvoiceId && !loadingImportLines && (showImportLinePicker = true)}
                                            tabindex={!selectedImportInvoiceId || loadingImportLines ? -1 : 0}
                                            onkeydown={(event) =>
                                                openOnEnterOrSpace(
                                                    event,
                                                    () =>
                                                        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">{m['invoice_item_fa.repair.type_search_label']()}</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 || m['invoice_item_fa.repair.search_placeholder']()}
                                            </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">{m['invoice_item_fa.main_data.legend']()}</h3>
                                </div>
                                <div class="p-3 bg-zinc-50 dark:bg-zinc-800/30 rounded-lg border border-zinc-200 dark:border-zinc-700/50">
                                    {#if editingItem.quantity && editingItem.financial && editingItem.customs}
                                        <MainData 
                                            bind:lineItem={editingItem}
                                            bind:quantities={editingItem.quantity}
                                            bind:financials={editingItem.financial}
                                            bind:customs={editingItem.customs}
                                            {invoice}
                                            disabled={isReadOnly}
                                        />
                                    {/if}

                                </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">{m['invoice_item_fa.configuration']?.() || 'Configuración'}</h3>
                                </div>
                                <div class="p-2">
                                    {#if editingItem.description}
                                        <ItemConfiguration 
                                            bind:lineItem={editingItem}
                                            bind:descriptions={editingItem.description}
                                            disabled={isReadOnly}
                                        />
                                    {/if}
                                </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">
                                    {#if editingItem.description && editingItem.customs && editingItem.quantity}
                                        <PackagesSection 
                                            bind:item={editingItem}
                                            bind:lineItem={editingItem}
                                            bind:descriptions={editingItem.description}
                                            bind:customs={editingItem.customs}
                                            bind:quantities={editingItem.quantity}
                                            invoice={invoice}
                                            disabled={isReadOnly}
                                        />
                                    {/if}
                                    {#if editingItem.financial && editingItem.quantity}
                                        <SummarySection 
                                            bind:financials={editingItem.financial}
                                            bind:quantities={editingItem.quantity}
                                            lineItem={editingItem}
                                            invoice={invoice}
                                            disabled={isReadOnly}
                                        />
                                    {/if}


                                </div>
                            </Tabs.Content>

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

                            <Tabs.Content value="series" class="m-0 focus-visible:outline-none">
                                {#if editingItem.description && editingItem.series}
                                    <TabSeries
                                        bind:descriptions={editingItem.description}
                                        bind:series={editingItem.series}
                                        lineItem={editingItem}
                                        {invoice}
                                        disabled={isReadOnly}
                                    />
                                {/if}
                            </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} 
                                        disabled={isReadOnly}
                                    />
                                </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}
                                        disabled={isReadOnly}
                                    />
                                </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">{m['invoice_item_fa.repair.loading_item_data']()}</p>
                    </div>
                {/if}
            </div>
        </div>

        <footer
            class="bg-white dark:bg-zinc-950 border-t border-zinc-200 dark:border-zinc-800 shadow-sm shrink-0"
		>
            {#if saveError?.length}
                <div class="flex items-start gap-2 border-b border-destructive/20 bg-destructive/5 px-3 py-2">
                    <AlertCircle class="mt-0.5 size-3.5 shrink-0 text-destructive" />
                    <div class="min-w-0 flex-1 space-y-0.5">
                        {#each saveError as row}
                            <p class="text-xs text-destructive">
                                {#if row.field}<span class="font-semibold">{row.field}: </span>{/if}{row.message}
                            </p>
                        {/each}
                    </div>
                    <button
                        type="button"
                        class="shrink-0 text-destructive/70 hover:text-destructive"
                        onclick={() => onDismissSaveError?.()}
                        aria-label="Cerrar error"
                    >
                        <X class="size-3.5" />
                    </button>
                </div>
            {/if}
            <div class="flex items-center justify-end gap-1.5 px-3 py-1.5">
                <Button variant="outline" size="sm" onclick={() => onCancel?.()} disabled={isSaving} class="h-7 text-xs px-2">
                    {isReadOnly ? m['invoice_item_fa.repair.close']() : m['invoice_item_fa.repair.cancel']()}
                </Button>
                
                {#if !isReadOnly}
                    <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" />
                            {m['invoice_item_fa.repair.loading_line']()}
                        {:else}
                            <Save class="w-3 h-3 mr-1" />
                            {m['invoice_item_fa.repair.save']()}
                        {/if}
                    </Button>
                {/if}
            </div>
        </footer>

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

<InvoiceSelectorModal
	bind:open={showImportInvoiceModal}
	regimen={editingItem.fa_data?.movement_type_import === 'DEF' ? 'Definitiva' : 'Temporal'}
	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">{m['invoice_item_fa.repair.select_line_title']()}</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;
                    }}
                >
                    {m['invoice_item_fa.repair.line_label']()} {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-5xl max-h-[90vh] flex flex-col p-0 overflow-hidden bg-slate-50 dark:bg-zinc-950 border-zinc-200 dark:border-zinc-800">
        <Dialog.Header class="p-6 pb-2">
            <div class="flex items-center gap-2 mb-1">
                <div class="p-1.5 bg-zinc-100 dark:bg-zinc-800 rounded-lg">
                    <FileText class="w-5 h-5 text-zinc-900 dark:text-zinc-100" />
                </div>
                <Dialog.Title class="text-xl font-bold tracking-tight">{m['invoice_item_fa.repair.import_title']()}</Dialog.Title>
            </div>
            <Dialog.Description class="text-sm text-muted-foreground ml-9">
                {m['invoice_item_fa.repair.import_description']()}
            </Dialog.Description>
        </Dialog.Header>

        <div class="flex-1 overflow-y-auto px-6 py-4">
            {#if loadingImportLines}
                <div class="flex flex-col items-center justify-center py-20 text-muted-foreground animate-pulse">
                    <Loader2 class="w-8 h-8 animate-spin mb-4 text-blue-500" />
                    <p class="text-sm font-medium">{m['invoice_item_fa.repair.loading_invoice_items']()}</p>
                </div>
            {:else if importInvoiceLines.every(l => !l.has_balance)}
                <div class="flex flex-col items-center justify-center py-20 text-zinc-400 bg-white dark:bg-zinc-900 rounded-xl border border-dashed border-zinc-200 dark:border-zinc-800">
                    <X class="w-8 h-8 mb-2 opacity-20" />
                    <p class="text-sm font-medium">{m['invoice_item_fa.repair.no_balance']()}</p>
                    <p class="text-xs">{m['invoice_item_fa.repair.no_balance_description']()}</p>
                </div>
            {:else}
                <div class="grid grid-cols-1 gap-3">
                    {#each importInvoiceLines as lineItem}
                        {#if lineItem.has_balance}
                            <button
                                class="group flex flex-col p-4 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-xl hover:border-blue-500 dark:hover:border-blue-600 hover:shadow-lg transition-all text-left"
                                disabled={loadingImportDetails}
                                onclick={async () => {
                                    if (loadingImportDetails || !companyStore?.activeCompany?.id) return;
                                    
                                    try {
                                        loadingImportDetails = true;
                                        
                                        // 1. Fetch full import item (ASIGNA_INFO_IMPO_TEM)
                                        const res = await itemsApi.get(lineItem.id, companyStore.activeCompany.id);
                                        const fullImportItem = res.data;
                                        if (!fullImportItem) {
                                            throw new Error("No se pudo cargar la información de la partida de importación.");
                                        }
                                        
                                        // 2. Initialize missing objects
                                        editingItem.fa_data = editingItem.fa_data || {};
                                        editingItem.quantity = editingItem.quantity || {};
                                        editingItem.financial = editingItem.financial || {};
                                        editingItem.customs = editingItem.customs || {};
                                        editingItem.description = editingItem.description || {};
                                        
                                        // 3. Identification & Basic Info
                                        editingItem.fa_data.search_line = lineItem.line_number;
                                        editingItem.fa_data.discharge = true; 
                                        editingItem.part_number = fullImportItem.part_number;
                                        editingItem.part_number_id = fullImportItem.part_number_id;
                                        (editingItem as any).part_number_display = fullImportItem.part_number;
                                        (editingItem as any).part_description_es = fullImportItem.description?.description_spanish;
                                        (editingItem as any).part_description_en = fullImportItem.description?.description_english;
                                        editingItem.class_id = fullImportItem.class_id;
                                        editingItem.class_code = fullImportItem.class_code;
                                        editingItem.unit_of_measure = fullImportItem.unit_of_measure;
                                        editingItem.unit_of_measure_code = fullImportItem.unit_of_measure_code;
                                        
                                        // 4. Source Data for Proportional Calculations
                                        // (Keep user typed quantity, or default to import quantity if missing)
                                        if (!editingItem.quantity.quantity) editingItem.quantity.quantity = fullImportItem.quantity?.quantity || 0;
                                        editingItem.fa_data.source_quantity = fullImportItem.quantity?.quantity || 1;
                                        editingItem.fa_data.source_balance = lineItem.available_balance;
                                        editingItem.fa_data.source_net_weight = fullImportItem.quantity?.net_weight || 0;
                                        editingItem.fa_data.source_gross_weight = fullImportItem.quantity?.gross_weight || 0;
                                        editingItem.fa_data.source_packages = fullImportItem.quantity?.package_quantity || 0;
                                        editingItem.quantity.package_id = fullImportItem.quantity?.package_id;
                                        
                                        // 5. Descriptions & Customs
                                        editingItem.description.description_spanish = fullImportItem.description?.description_spanish;
                                        editingItem.description.description_english = fullImportItem.description?.description_english;
                                        editingItem.description.extra_description = fullImportItem.description?.extra_description;
                                        editingItem.description.brand = fullImportItem.description?.brand;
                                        editingItem.description.model = fullImportItem.description?.model;
                                        
                                        editingItem.customs.fraction = fullImportItem.customs?.fraction;
                                        editingItem.customs.fraction_type = fullImportItem.customs?.fraction_type;
                                        editingItem.customs.american_fraction = fullImportItem.customs?.american_fraction;
                                        editingItem.customs.origin_country = fullImportItem.customs?.origin_country;
                                        editingItem.customs.sector = fullImportItem.customs?.sector;
                                        
                                        // 6. Costs (Triangulate based on Export Currency vs USD base)
                                        const importCostUsd = fullImportItem.financial?.unit_cost_usd || 0;
                                        const exportCurrency = invoice?.financials?.currency_type || 'USD';
                                        const exportExRate = Number(invoice?.financials?.exchange_rate || 1);
                                        
                                        if (exportCurrency === 'USD' || exportCurrency === 'ME' || exportCurrency === 'FOREIGN') {
                                            editingItem.financial.unit_cost_capture = importCostUsd;
                                        } else if (exportCurrency === 'MXN' || exportCurrency === 'MN' || exportCurrency === 'LOCAL') {
                                            editingItem.financial.unit_cost_capture = importCostUsd * exportExRate;
                                        } else {
                                            editingItem.financial.unit_cost_capture = importCostUsd;
                                        }
                                        
                                        // 7. Copy Series (Remove original ID to insert as new array)
                                        if (fullImportItem.series && fullImportItem.series.length > 0) {
                                            editingItem.series = fullImportItem.series.map((s: any) => ({
                                                ...s,
                                                id: undefined,
                                                line_item_id: undefined,
                                                discharge: true
                                            }));
                                            editingItem.description.has_serial = true;
                                        } else {
                                            editingItem.description.has_serial = false;
                                        }
                                        
                                        // 8. Trigger calculation side effects
                                        recalculateWeights();
                                        
                                        showImportLinePicker = false;
                                    } catch (err) {
                                        console.error('Error auto-filling import info:', err);
                                    } finally {
                                        loadingImportDetails = false;
                                    }
                                }}
                            >
                                <!-- Header Row: Line #, Invoice, Status -->
                                <div class="flex items-center justify-between mb-3">
                                    <div class="flex items-center gap-3">
                                        <div class="bg-blue-600 text-white text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wider">
                                            Línea {lineItem.line_number}
                                        </div>
                                        <div class="text-[10px] font-mono font-medium text-muted-foreground px-2 py-0.5 bg-zinc-100 dark:bg-zinc-800 rounded border border-zinc-200 dark:border-zinc-700">
                                            Factura: {lineItem.invoice_number ?? '-'}
                                        </div>
                                    </div>
                                    <div class="flex items-center gap-2">
                                        {#if lineItem.invoice_status === 'processed'}
                                            <span class="inline-flex items-center rounded-full bg-emerald-100 dark:bg-emerald-900/40 px-2 py-0.5 text-[10px] font-bold text-emerald-700 dark:text-emerald-300 uppercase">
                                                Procesada
                                            </span>
                                        {/if}
                                        {#if lineItem.is_subitem}
                                            <span class="inline-flex items-center rounded-full bg-purple-100 dark:bg-purple-900/40 px-2 py-0.5 text-[10px] font-bold text-purple-700 dark:text-purple-300 uppercase">
                                                Subpartida
                                            </span>
                                        {/if}
                                    </div>
                                </div>

                                <!-- Main Body Grid -->
                                <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                                    <!-- Column 1: Part & Class -->
                                    <div class="col-span-1 space-y-1">
                                        <p class="text-[10px] font-bold text-zinc-400 uppercase tracking-tighter">Número de Parte / Clase</p>
                                        <p class="text-sm font-bold text-zinc-900 dark:text-zinc-100 truncate">
                                            {lineItem.part_number ?? '-'}
                                        </p>
                                        <p class="text-xs font-medium text-blue-600 dark:text-blue-400">
                                            {lineItem.class_code ?? 'Sin Clase'}
                                        </p>
                                    </div>

                                    <!-- Column 2: Description -->
                                    <div class="col-span-1 md:col-span-1 space-y-1">
                                        <p class="text-[10px] font-bold text-zinc-400 uppercase tracking-tighter">Descripción</p>
                                        <p class="text-xs text-zinc-600 dark:text-zinc-400 line-clamp-2 italic" title={lineItem.description_spanish}>
                                            {lineItem.description_spanish || m['invoice_item_fa.repair.no_description']()}
                                        </p>
                                    </div>

                                    <!-- Column 3: Stats (Imported, Used) -->
                                    <div class="col-span-1 flex flex-col justify-center gap-2 border-l border-zinc-200 dark:border-zinc-800 pl-4">
                                        <div class="flex items-center justify-between text-[10px]">
                                            <span class="text-muted-foreground uppercase font-medium">Cant. Imp:</span>
                                            <span class="font-mono font-bold text-zinc-700 dark:text-zinc-300">
                                                {lineItem.quantity?.toLocaleString() || '0'} {lineItem.unit_of_measure_code || ''}
                                            </span>
                                        </div>
                                        <div class="flex items-center justify-between text-[10px]">
                                            <span class="text-muted-foreground uppercase font-medium">Desc. Temp:</span>
                                            <span class="font-mono font-bold text-amber-600 dark:text-amber-400">
                                                -{lineItem.quantity_used_temp?.toLocaleString() || '0'}
                                            </span>
                                        </div>
                                    </div>

                                    <!-- Column 4: Available Balance (Prominent) -->
                                    <div class="col-span-1 flex flex-col items-end justify-center bg-blue-50/50 dark:bg-blue-900/10 rounded-lg p-3 border border-blue-100/50 dark:border-blue-900/30">
                                        <p class="text-[9px] font-bold text-blue-600/70 dark:text-blue-400/70 uppercase tracking-widest mb-1">Saldo Disponible</p>
                                        <div class="flex items-baseline gap-1">
                                            <span class="text-xl font-black text-blue-700 dark:text-blue-400 tabular-nums">
                                                {lineItem.available_balance.toLocaleString('es-MX', { maximumFractionDigits: 4 })}
                                            </span>
                                            <span class="text-[10px] font-bold text-blue-600 dark:text-blue-400 uppercase">
                                                {lineItem.unit_of_measure_code ?? ''}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mt-4 pt-3 border-t border-zinc-100 dark:border-zinc-800/50 flex items-center justify-between">
                                    <div class="text-[9px] text-zinc-400 flex items-center gap-1">
                                        <Calendar class="w-3 h-3" />
                                        Fecha: {lineItem.invoice_date ? lineItem.invoice_date.slice(0, 10) : m['invoice_item_fa.item_sheet.not_available_short']()}
                                    </div>
                                    <div class="opacity-0 group-hover:opacity-100 transition-opacity">
                                        <span class="text-[10px] font-bold text-blue-600 dark:text-blue-400 uppercase tracking-widest">Hacer descarga &rarr;</span>
                                    </div>
                                </div>
                            </button>
                        {/if}
                    {/each}
                </div>
            {/if}
        </div>

        <Dialog.Footer class="p-4 bg-white dark:bg-zinc-950 border-t border-zinc-200 dark:border-zinc-800 flex items-center justify-between px-6">
            <p class="text-[10px] font-medium text-muted-foreground uppercase tracking-widest">
                Mostrando {importInvoiceLines.filter(l => l.has_balance).length} partidas con saldo
            </p>
            <Button variant="ghost" size="sm" class="text-xs font-semibold" onclick={() => (showImportLinePicker = false)}>
                Cerrar
            </Button>
        </Dialog.Footer>
    </Dialog.Content>
</Dialog.Root>