<script lang="ts">
    import * as Sheet from '$lib/components/ui/sheet';
    import * as Tabs from '$lib/components/ui/tabs';
    import { Button } from '$lib/components/ui/button';
    import { Separator } from '$lib/components/ui/separator';
    import { Loader2, Package, Save, X, FileText } from 'lucide-svelte';
    import type { Invoice } from '$lib/api/dashboard/a76/invoices';
    import type { Item } from '$lib/api/dashboard/a76/items';
    
    // Child components
    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';

    let { 
        open = $bindable(),
        isEditMode = false,
        editingItem = $bindable(),
        invoice,
        onSave,
        onCancel,
        isTargetingPreset = false,
        isSaving = false
    }: { 
        open: boolean;
        isEditMode?: boolean;
        editingItem: Partial<Item>;
        invoice: Invoice | 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);
</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}
                    <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 value="generales" class="w-full">
                        <Tabs.List class="grid w-full grid-cols-5 bg-zinc-100 dark:bg-zinc-800/50 rounded p-0.5 gap-0.5">
                            <Tabs.Trigger value="generales" 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">
                                General
                            </Tabs.Trigger>
                            <Tabs.Trigger value="continuacion" 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">
                                Continuación
                            </Tabs.Trigger>
                            <Tabs.Trigger value="series" 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">
                                Series
                            </Tabs.Trigger>
                            <Tabs.Trigger value="etiquetado" 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">
                                Etiquetado
                            </Tabs.Trigger>
                            <Tabs.Trigger value="identificadores" 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">
                                IDs
                            </Tabs.Trigger>
                        </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!}
                                />
                            </Tabs.Content>

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

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

                            <Tabs.Content value="identificadores" class="m-0 focus-visible:outline-none">
                                <TabIdentifiers bind:lineItem={editingItem} />
                            </Tabs.Content>
                        </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>