<script lang="ts">
    import { goto } from '$app/navigation';
    
    // UI Components
    import { Button } from '$lib/components/ui/button';
    import { Input } from '$lib/components/ui/input';
    import { Label } from '$lib/components/ui/label';
    import { Textarea } from '$lib/components/ui/textarea';
    import * as Tabs from '$lib/components/ui/tabs';
    import * as Card from '$lib/components/ui/card';
    import * as Select from "$lib/components/ui/select";
    import { Switch } from "$lib/components/ui/switch";
    import { Separator } from '$lib/components/ui/separator';
    import { Badge } from '$lib/components/ui/badge'; 
    
    // Iconos
    import { 
        ArrowLeft, LoaderCircle, Save, Package, DollarSign, 
        FileText, Settings, Image as ImageIcon, FolderSearch,
        UserCheck, CheckCircle2, XCircle, Tag, Layers, Scale, Info, Briefcase, ShieldCheck, Globe
    } from 'lucide-svelte';
    import { toast } from "svelte-sonner";

    // Stores & APIs
    import { companyStore } from '$lib/stores/company.svelte';
    import { partsApi } from '$lib/api/dashboard/a76/parts';
    import { clientsProvidersApi } from '$lib/api/dashboard/a76/clients-providers';
    import { classesApi } from '$lib/api/dashboard/a76/classes'; 
    import { materialTypesApi } from '$lib/api/dashboard/a76/material-types'; 

    // Modales
    import ClientSelectorDialog from '$lib/components/dashboard/goods/modales/client-selector-dialog.svelte';
    import ClassSelectorDialog from '$lib/components/dashboard/goods/parts/class-selector-dialog.svelte';
    import MaterialTypeSelectorDialog from '$lib/components/dashboard/goods/modales/material-type-selector-dialog.svelte';
    import UnitMeasureSelectorDialog from '$lib/components/dashboard/goods/modales/unit-measure-dialog.svelte';
    import CurrencySelectorDialog from '$lib/components/dashboard/goods/modales/currency-selector-dialog.svelte';
    import CountrySelectorDialog from '$lib/components/dashboard/goods/modales/country-selector-dialog.svelte';
    import FractionSelectorDialog from '$lib/components/dashboard/goods/modales/fraction-selector-dialog.svelte';
    import USFractionSelectorDialog from '$lib/components/dashboard/goods/modales/us-fraction-selector-dialog.svelte';
    import { useShortcuts } from '$lib/hooks/use-shortcuts';
    import { obtenerAtajosFormularioMercancia } from '$lib/config/shortcuts/dashboard/goods/edit';

    // --- PROPS ---
    let { partId = null, formType = 'inv' }: { partId?: number | null, formType?: 'inv' | 'fa' } = $props();

    // --- LÓGICA DE ESTADO ---
    let isEdit = $derived(!!partId);
    let title = $derived(isEdit ? "Editar Parte" : "Nueva Parte");

    let loading = $state(false);
    let error = $state<string | null>(null);
    let activeTab = $state('general');

    // Estado Modales
    let showClientModal = $state(false);
    let showClassModal = $state(false);
    let showMaterialModal = $state(false);
    let showUOMModal = $state(false);
    let showAltUOMModal = $state(false); 
    let showCurrencyModal = $state(false);
    let showCountryModal = $state(false);
    let showFractionModal = $state(false);
    let showUSFractionModal = $state(false);

    // Descripciones Visuales
    let selectedClientName = $state(""); 
    let selectedClientStatus = $state(true); 
    let selectedClassDesc = $state("");
    let selectedCurrencyName = $state("");
    let selectedCountryName = $state("");
    let selectedMaterialDesc = $state("");

    // Estado Formulario
    let formData = $state({
        client_id: 0,
        part_number: '',
        description_spanish: '',
        description_english: '',
        part_class: '',          
        material_type: '',       
        unit_of_measure: '',   
        unit_weight: 0,
        weight_type: 'KG',
        unit_cost: 0,
        currency_type: '',
        currency_key: null as string | null,
        added_value: 0,
        value_added_type: 'USD',
        us_fraction: '',
        supplier: '',
        fcc_key: '',
        part_photo: '',
        fda_key: '',
        commercial_part_number: '',
        alternate_unit_measure: '', 
        fraction: '', 
        eccn: '',
        license_code: '',
        export_code: '',
        exclusion_symbol: '',
        is_active: true,
        // --- CAMPOS ESPECIFICOS DE FA (Activos Fijos) ---
        origin_country: 'MEX',
        sector: '',
        fraction_type: ''
    });

    // --- CARGA DE DATOS ---
    $effect(() => {
        if (companyStore.activeCompany?.id && partId) {
            loadPartData(partId, companyStore.activeCompany.id);
        }
    });

    async function loadPartData(id: number, companyId: number) {
        loading = true;
        try {
            const response = await partsApi.get(id, companyId);
            if (response.data) {
                const d = response.data;
                formData = {
                    client_id: d.client_id,
                    part_number: d.part_number,
                    description_spanish: d.description_spanish || '',
                    description_english: d.description_english || '',
                    part_class: d.part_class || '',
                    material_type: d.inv_data?.material_type || '', 
                    origin_country: d.fa_data?.origin_country || 'MEX',
                    unit_of_measure: d.unit_of_measure || '',
                    fraction: d.fraction || '',
                    us_fraction: d.us_fraction || '',
                    unit_weight: Number(d.unit_weight) || 0,
                    weight_type: d.weight_type || 'KG',
                    supplier: d.inv_data?.supplier_code || '',
                    fda_key: d.fda_key || '',
                    fcc_key: d.fcc_key || '',
                    eccn: d.eccn || '',
                    license_code: d.license_code || '',
                    export_code: d.export_code || '',
                    exclusion_symbol: d.exclusion_symbol || '',
                    unit_cost: Number(d.unit_cost) || 0,
                    currency_key: d.currency_key || 'USD',
                    added_value: Number(d.inv_data?.added_value) || 0,
                    value_added_type: 'USD', 
                    commercial_part_number: d.commercial_part_number || '',
                    alternate_unit_measure: d.inv_data?.alternate_uom || '',
                    part_photo: d.part_photo || '',
                    is_active: d.is_active ?? true,
                    sector: d.fa_data?.sector || '',
                    fraction_type: d.fa_data?.fraction_type || '',
                    currency_type: '' // Initialize to match type
                };
                // Ensure currency_type is mapped correctly if coming from DB (optional, depending on DB values)
                if (d.currency_key === 'MXN') formData.currency_type = 'NA';
                else if (d.currency_key === 'USD') formData.currency_type = 'EX';

                if (d.client_id) await fetchClientName(d.client_id, companyId);
                if (d.part_class) await fetchClassDesc(d.part_class, companyId);
                if (d.inv_data?.material_type) await fetchMaterialName(d.inv_data.material_type);
            }
        } catch (e) { console.error(e); } finally { loading = false; }
    }

    // --- EFECTOS REACTIVOS ---
    $effect(() => {
        // Auto-set currency based on type selection
        if (formData.currency_type === 'NA') {
            formData.currency_key = 'MXN';
            selectedCurrencyName = 'MXN';
        } else if (formData.currency_type === 'EX') {
            formData.currency_key = 'USD';
            selectedCurrencyName = 'USD';
        }
    });

    // --- HELPERS VISUALES ---
    async function fetchClientName(clientId: number, companyId: number) {
        try {
            const res = await clientsProvidersApi.get(clientId, companyId);
            const clientData = (res as any).data || res;
            if (clientData) {
                selectedClientName = clientData.name;
                selectedClientStatus = clientData.is_active ?? true;
            }
        } catch (e) { console.error("Error visual cliente", e); }
    }

    async function fetchClassDesc(code: string, companyId: number) {
        try {
            const res = await classesApi.list({ company_id: companyId, class_code: code });
            const data = (res as any).data || res;
            const list = data.items || data.classes || [];
            if (list.length > 0) {
                const found = list.find((i: any) => i.class_code === code) || list[0];
                selectedClassDesc = found.description_es || found.description_en || "";
            }
        } catch (e) { console.error("Error visual clase", e); }
    }

    async function fetchMaterialName(key: string) {
        try {
            const res = await materialTypesApi.list(1, 100);
            const data = (res as any).data || res;
            const list = data.items || [];
            const found = list.find((m: any) => m.key === key);
            if (found) selectedMaterialDesc = found.description;
        } catch (e) { console.error("Error visual material", e); }
    }

    // --- HANDLERS ---
    function handleClientSelect(client: any) { formData.client_id = client.id; selectedClientName = client.name; selectedClientStatus = client.is_active ?? true; }
    function handleClassSelect(item: any) { formData.part_class = item.class_code; selectedClassDesc = item.description_es || item.description_en || ""; }
    function handleMaterialSelect(item: any) { formData.material_type = item.key; selectedMaterialDesc = item.description; }
    function handleUOMSelect(item: any) { formData.unit_of_measure = item.code; }
    function handleAltUOMSelect(item: any) { formData.alternate_unit_measure = item.code; }
    function handleCurrencySelect(currency: any) { 
        formData.currency_type = ''; // Reset type legacy field
        // FIX: Usar 'code' de la API pública currency_types
        const code = currency.code || currency.currency_type_code; 
        formData.currency_key = code;
        selectedCurrencyName = code; 
    }
    function handleCountrySelect(country: any) { 
        // FIX: Asegurar que se asigna la clave correcta
        formData.origin_country = country.m3_key || country.country_key; 
        selectedCountryName = country.description_es; 
    }
    function handleFractionSelect(item: any) { formData.fraction = item.fraction; }
    function handleUSFractionSelect(item: any) { formData.us_fraction = item.code; }

    // --- SUBMIT ---
    async function handleSubmit() {
        error = null;
        const activeCompanyId = companyStore.activeCompany?.id;
        if (!activeCompanyId) { error = 'No hay una compañía activa seleccionada'; return; }
        if (!formData.client_id) { error = 'Debe seleccionar un Cliente'; return; }
        if (!formData.unit_of_measure) { error = 'Debe seleccionar una Unidad de Medida'; return; }
        
        loading = true;
        try {
            let commonData: any = { ...formData };
            if (!commonData.currency_key || commonData.currency_key === 'USD') {
                commonData.currency_key = null;
            }
            if (formType === 'fa') {
                commonData.fa_data = {
                    sector: formData.sector,
                    fraction_type: formData.fraction_type,
                    origin_country: formData.origin_country
                };
                delete commonData.sector;
                delete commonData.fraction_type;
                delete commonData.origin_country;
            }        

            if (isEdit && partId) {
                // TODO: Verify partId is number/string as expected
                const res = await partsApi.update(Number(partId), commonData, activeCompanyId);                
                if (res.error) throw new Error(res.error);
            } else {
                const result = await partsApi.create({ ...commonData, company_id: activeCompanyId }, activeCompanyId);                
                if (result.error) { error = result.error; return; }
            }
            toast.success(isEdit ? "Parte actualizada" : "Parte creada");
            goto('/dashboard/goods/parts');
        } catch (e: any) { 
            console.error("Submit Error:", e);
            error = e.message || 'Error al guardar'; 
            toast.error(error!);
        } finally { loading = false; }
    }
    // Shortcuts
    useShortcuts('Part Form', obtenerAtajosFormularioMercancia({
        cambiarPestana: (pestana: string) => activeTab = pestana,
        manejarGuardar: handleSubmit,
        manejarRegresar: () => goto('/dashboard/goods/parts')
    }));
</script>

<div class="space-y-4">
    <div class="flex items-center justify-between">
        <div class="space-y-1">
            <div class="flex items-center gap-3">
                <Button variant="ghost" size="icon" href="/dashboard/goods/parts">
                    <ArrowLeft size={20} />
                </Button>
                <h1 class="text-3xl font-bold tracking-tight">{title}</h1>
                <Badge variant={isEdit ? "secondary" : "default"}>
                    {isEdit ? "Editar" : "Nueva"}
                </Badge>
            </div>
            <p class="text-muted-foreground ml-11">
                {formType === 'fa' ? 'Gestión de Activo Fijo' : 'Gestión de Inventario'}
            </p>
        </div>
    </div>

    <Separator />

    {#if error}
        <div class="p-4 rounded-md bg-destructive/10 text-destructive border border-destructive/20 text-sm font-medium animate-in slide-in-from-top-2">
            ⚠️ {error!}
        </div>
    {/if}

    <div class="pb-48">

    {#if formType === 'fa'}
        <form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="space-y-6">
            <Card.Root class="shadow-sm">
                <Card.Content class="p-6">
                    <Tabs.Root bind:value={activeTab} class="w-full">
                        
                        <div class="min-h-[500px]">
                            <Tabs.Content value="general" class="space-y-8 pt-6 animate-in fade-in duration-300">
                                
                                <div class="grid grid-cols-1 md:grid-cols-12 gap-6">
                                    <div class="md:col-span-6 space-y-2">
                                        <Label for="fa_pn" class="text-base font-semibold required">Número de Parte</Label>
                                        <div class="relative">
                                            <Package class="absolute left-3 top-2.5 h-5 w-5 text-muted-foreground" />
                                            <Input id="fa_pn" bind:value={formData.part_number} disabled={isEdit} maxlength={50} class="pl-10 text-lg font-mono bg-muted/20" placeholder="Ej: MAQ-001"/>
                                        </div>
                                    </div>
                                    <div class="md:col-span-6 space-y-2">
                                        <Label for="fa_client" class="text-base font-semibold required">Cliente Asignado</Label>
                                        <div class="flex gap-2">
                                            <div class="relative w-full">
                                                <UserCheck class="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                                                <Input id="fa_client" bind:value={selectedClientName} readonly onclick={() => showClientModal = true} class="pl-9 cursor-pointer hover:bg-muted/50 transition-colors" placeholder="Seleccione un cliente..."/>
                                            </div>
                                            <Button variant="secondary" size="icon" type="button" onclick={() => showClientModal = true} class="shrink-0"><FolderSearch class="h-4 w-4" /></Button>
                                        </div>
                                    </div>
                                </div>

                                <div class="grid grid-cols-1 md:grid-cols-12 gap-6">
                                    <div class="md:col-span-6 space-y-2">
                                        <Label for="fa_desc_es" class="flex items-center gap-2">Descripción Español <span class="text-xs text-muted-foreground font-normal">(Requerido)</span></Label>
                                        <Textarea id="fa_desc_es" bind:value={formData.description_spanish} rows={3} class="resize-none" placeholder="Descripción detallada en español..."/>
                                    </div>
                                    <div class="md:col-span-6 space-y-2">
                                        <Label for="fa_desc_en" class="flex items-center gap-2">Descripción Inglés</Label>
                                        <Textarea id="fa_desc_en" bind:value={formData.description_english} rows={3} class="resize-none" placeholder="English description..."/>
                                    </div>
                                </div>

                                <div class="grid grid-cols-1 md:grid-cols-12 gap-6">
                                    <div class="md:col-span-4 space-y-2">
                                        <Label for="fa_class" class="required">Clase</Label>
                                        <div class="flex gap-2">
                                            <Input id="fa_class" bind:value={formData.part_class} readonly onclick={() => showClassModal = true} class="cursor-pointer font-mono" placeholder="Seleccione..."/>
                                            <Button variant="outline" size="icon" type="button" onclick={() => showClassModal = true} class="shrink-0"><FolderSearch class="h-4 w-4" /></Button>
                                        </div>
                                        {#if selectedClassDesc}<p class="text-[11px] text-muted-foreground truncate px-1">{selectedClassDesc}</p>{/if}
                                    </div>

                                    <div class="md:col-span-4 space-y-2">
                                        <Label for="fa_uom" class="required">Unidad Medida</Label>
                                        <div class="flex gap-2">
                                            <div class="relative w-full">
                                                <Scale class="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                                                <Input id="fa_uom" bind:value={formData.unit_of_measure} readonly onclick={() => showUOMModal = true} class="pl-9 cursor-pointer font-mono" placeholder="Seleccione..."/>
                                            </div>
                                            <Button variant="outline" size="icon" type="button" onclick={() => showUOMModal = true} class="shrink-0"><FolderSearch class="h-4 w-4" /></Button>
                                        </div>
                                    </div>

                                    <div class="md:col-span-4 space-y-2">
                                        <Label for="fa_origin">País Origen</Label>
                                        <div class="flex gap-2">
                                            <div class="relative w-full">
                                                <Globe class="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                                                <Input id="fa_origin" bind:value={selectedCountryName} readonly onclick={() => showCountryModal = true} class="pl-9 cursor-pointer" placeholder="Seleccione..."/>
                                            </div>
                                            <Button variant="outline" size="icon" type="button" onclick={() => showCountryModal = true} class="shrink-0"><FolderSearch class="h-4 w-4" /></Button>
                                        </div>
                                    </div>
                                </div>

                                <div class="p-5 border rounded-xl bg-slate-50 dark:bg-slate-900/30 space-y-4">
                                    <h3 class="font-semibold text-sm text-primary flex items-center gap-2">
                                        <DollarSign class="h-4 w-4"/> Información Financiera y Pesos
                                    </h3>
                                    <Separator class="bg-primary/10" />
                                    <div class="grid grid-cols-1 md:grid-cols-12 gap-6 pt-2">
                                        <div class="md:col-span-4 space-y-2">
                                            <Label for="fa_cost">Costo Unitario</Label>
                                            <div class="relative">
                                                <span class="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground font-semibold text-sm">$</span>
                                                <Input type="number" step="0.0001" id="fa_cost" bind:value={formData.unit_cost} class="pl-7 h-10" placeholder="0.0000" />
                                            </div>
                                        </div>

                                        <div class="md:col-span-4 space-y-2">
                                            <Label>Moneda</Label>
                                            <div class="space-y-2">
                                                <Button variant="outline" type="button" onclick={() => { formData.currency_type = 'CATALOG'; showCurrencyModal = true; }} class="w-full h-10 justify-between font-normal px-3">
                                                    <span class="flex items-center gap-2 text-muted-foreground"><FolderSearch class="h-4 w-4" /> {selectedCurrencyName || 'Catálogo'}</span>
                                                </Button>
                                                <div class="flex gap-4 mb-2">
                                                    <label class="text-xs flex items-center gap-2 cursor-pointer hover:text-primary transition-colors">
                                                        <input type="radio" name="fa_currency_type" value="NA" bind:group={formData.currency_type} class="accent-primary" /> Nacional
                                                    </label>
                                                    <label class="text-xs flex items-center gap-2 cursor-pointer hover:text-primary transition-colors">
                                                        <input type="radio" name="fa_currency_type" value="EX" bind:group={formData.currency_type} class="accent-primary" /> Extranjera
                                                    </label>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="md:col-span-4 space-y-2">
                                            <Label for="fa_weight">Peso Unitario</Label>
                                            <div class="flex gap-2">
                                                <Input type="number" step="0.0001" id="fa_weight" bind:value={formData.unit_weight} placeholder="0.0000" />
                                                <Select.Root type="single" value={formData.weight_type} onValueChange={(v) => formData.weight_type = v}>
                                                    <Select.Trigger class="w-[85px]">{formData.weight_type}</Select.Trigger>
                                                    <Select.Content>
                                                        <Select.Item value="KG">KG</Select.Item>
                                                        <Select.Item value="LB">LB</Select.Item>
                                                    </Select.Content>
                                                </Select.Root>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="p-5 border rounded-xl space-y-4">
                                    <h3 class="font-semibold text-sm text-muted-foreground flex items-center gap-2">
                                        <Briefcase class="h-4 w-4"/> Clasificación Aduanera
                                    </h3>
                                    <div class="grid grid-cols-1 md:grid-cols-12 gap-6">
                                        <div class="md:col-span-6 space-y-2">
                                            <Label for="fa_fraction">Fracción UMT (MX)</Label>
                                            <div class="flex gap-2">
                                                <Input id="fa_fraction" bind:value={formData.fraction} readonly onclick={() => showFractionModal = true} class="cursor-pointer font-mono" placeholder="Seleccione..."/>
                                                <Button variant="outline" size="icon" type="button" onclick={() => showFractionModal = true} class="shrink-0"><FolderSearch class="h-4 w-4" /></Button>
                                            </div>
                                        </div>
                                        <div class="md:col-span-6 space-y-2">
                                            <Label for="fa_us_fraction">Fracción Americana</Label>
                                            <div class="flex gap-2">
                                                <Input id="fa_us_fraction" bind:value={formData.us_fraction} maxlength={10} class="font-mono cursor-pointer" placeholder="HTS Code" readonly onclick={() => showUSFractionModal = true}/>
                                                <Button variant="outline" size="icon" type="button" onclick={() => showUSFractionModal = true} class="shrink-0"><FolderSearch class="h-4 w-4" /></Button>
                                            </div>
                                        </div>
                                        <div class="md:col-span-6 space-y-2">
                                            <Label for="fa_sector">Sector</Label>
                                            <Input id="fa_sector" bind:value={formData.sector} maxlength={8} placeholder="Ej: VIII"/>
                                        </div>
                                        <div class="md:col-span-6 space-y-2">
                                            <Label for="fa_fraction_type">Tipo Tarifa</Label>
                                            <Input id="fa_fraction_type" bind:value={formData.fraction_type} maxlength={7} />
                                        </div>
                                    </div>
                                </div>

                                <div class="flex items-center gap-3 pt-2 pl-1">
                                    <Switch id="fa_is_active" bind:checked={formData.is_active} />
                                    <Label for="fa_is_active" class="cursor-pointer">Parte activa en sistema</Label>
                                </div>

                            </Tabs.Content>

                            <Tabs.Content value="cont1" class="space-y-6 pt-6 animate-in fade-in duration-300">
                                <div class="p-6 border rounded-xl space-y-4">
                                    <div class="max-w-2xl mx-auto space-y-4">
                                        <Label for="fa_photo" class="flex items-center gap-2 text-base">
                                            <ImageIcon class="h-5 w-5"/> URL Imagen de la parte
                                        </Label>
                                        <div class="flex gap-2">
                                            <Input id="fa_photo" bind:value={formData.part_photo} maxlength={255} placeholder="https://ejemplo.com/imagen.jpg" />
                                            <Button variant="outline" class="shrink-0">Vista Previa</Button>
                                        </div>
                                        {#if formData.part_photo}
                                            <div class="mt-4 aspect-video rounded-lg bg-muted flex items-center justify-center border overflow-hidden">
                                                <img src={formData.part_photo} alt="Vista previa" class="h-full w-full object-contain" />
                                            </div>
                                        {/if}
                                    </div>
                                </div>
                            </Tabs.Content>

                            <Tabs.Content value="cont2" class="space-y-6 pt-6 animate-in fade-in duration-300">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                                    <div class="p-5 border rounded-xl space-y-4">
                                        <h3 class="font-medium text-sm text-muted-foreground flex items-center gap-2"><ShieldCheck class="h-4 w-4"/> Control de Exportación</h3>
                                        <div class="grid gap-4">
                                            <div class="grid grid-cols-2 gap-4">
                                                <div class="space-y-2">
                                                    <Label for="fa_lic">License Code</Label>
                                                    <Input id="fa_lic" bind:value={formData.license_code} maxlength={3} class="font-mono" />
                                                </div>
                                                <div class="space-y-2">
                                                    <Label for="fa_exp">Export Code</Label>
                                                    <Input id="fa_exp" bind:value={formData.export_code} maxlength={2} class="font-mono" />
                                                </div>
                                            </div>
                                            <div class="space-y-2">
                                                <Label for="fa_eccn">ECCN</Label>
                                                <Input id="fa_eccn" bind:value={formData.eccn} maxlength={20} class="font-mono" />
                                            </div>
                                            <div class="space-y-2">
                                                <Label for="fa_exc">Símbolo Excepción Licencia</Label>
                                                <Input id="fa_exc" bind:value={formData.exclusion_symbol} maxlength={19} />
                                            </div>
                                        </div>
                                    </div>

                                    <div class="p-5 border rounded-xl space-y-4">
                                        <h3 class="font-medium text-sm text-muted-foreground flex items-center gap-2"><Info class="h-4 w-4"/> Regulaciones Adicionales</h3>
                                        <div class="space-y-4">
                                            <div class="space-y-2">
                                                <Label for="fa_fda">Clave FDA</Label>
                                                <Input id="fa_fda" bind:value={formData.fda_key} maxlength={20} />
                                            </div>
                                            <div class="space-y-2">
                                                <Label for="fa_fcc">Clave FCC</Label>
                                                <Input id="fa_fcc" bind:value={formData.fcc_key} maxlength={30} />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </Tabs.Content>

                        </div>
                    </Tabs.Root>
                </Card.Content>
            </Card.Root>
        </form>

    {:else}
        <form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="space-y-6">
            <Card.Root class="shadow-sm">
                <Card.Content class="p-6">
                    <Tabs.Root bind:value={activeTab} class="w-full">
                        
                        <div class="min-h-[500px]">
                            <Tabs.Content value="general" class="space-y-8 pt-6 animate-in fade-in duration-300">
                                
                                <div class="grid grid-cols-1 md:grid-cols-12 gap-6">
                                    <div class="md:col-span-4 space-y-2">
                                        <Label for="part_number" class="text-base font-semibold">Número de Parte</Label>
                                        <div class="relative">
                                            <Package class="absolute left-3 top-2.5 h-5 w-5 text-muted-foreground" />
                                            <Input id="part_number" bind:value={formData.part_number} disabled={isEdit} maxlength={50} class="pl-10 text-lg font-mono bg-muted/20" placeholder="Ej: 123-ABC-456"/>
                                        </div>
                                    </div>
                                </div>

                                <div class="p-5 border rounded-xl bg-slate-50 dark:bg-slate-900/30 space-y-4">
                                    <h3 class="font-medium text-sm text-muted-foreground flex items-center gap-2">
                                        <FileText class="h-4 w-4"/> Descripción de Mercancía
                                    </h3>
                                    <div class="grid grid-cols-1 md:grid-cols-12 gap-6">
                                        <div class="md:col-span-6 space-y-2">
                                            <Label for="desc_es">Español <span class="text-xs text-muted-foreground font-normal ml-1">(Principal)</span></Label>
                                            <Textarea id="desc_es" bind:value={formData.description_spanish} maxlength={500} rows={3} class="bg-background"/>
                                        </div>
                                        <div class="md:col-span-6 space-y-2">
                                            <Label for="desc_en">Inglés</Label>
                                            <Textarea id="desc_en" bind:value={formData.description_english} maxlength={500} rows={3} class="bg-background"/>
                                        </div>
                                    </div>
                                </div>

                                <div class="grid grid-cols-1 md:grid-cols-12 gap-6">
                                    <div class="md:col-span-6 space-y-2">
                                        <Label for="part_class_client" class="required">Clase (Anexo 24)</Label>
                                        <div class="flex gap-2">
                                            <div class="relative w-full">
                                                <Tag class="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                                                <Input id="part_class_client" bind:value={formData.part_class} maxlength={15} placeholder="Clase..." class="pl-9 font-mono"/>
                                            </div>
                                            <Button variant="outline" size="icon" type="button" onclick={() => showClassModal = true} class="shrink-0"><FolderSearch class="h-4 w-4" /></Button>
                                        </div>
                                        {#if selectedClassDesc}<p class="text-[11px] text-primary font-medium px-1">{selectedClassDesc}</p>{/if}
                                    </div>

                                    <div class="md:col-span-6 space-y-2">
                                        <Label for="part_class_material">Tipo Material <span class="text-xs text-muted-foreground font-normal ml-1">(Catálogo General)</span></Label>
                                        <div class="flex gap-2">
                                            <div class="relative w-full">
                                                <Layers class="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                                                <Input id="part_class_material" bind:value={formData.material_type} maxlength={8} placeholder="Seleccione Material..." class="pl-9 font-mono cursor-pointer" readonly onclick={() => showMaterialModal = true}/>
                                            </div>
                                            <Button variant="outline" size="icon" type="button" onclick={() => showMaterialModal = true} class="shrink-0"><FolderSearch class="h-4 w-4" /></Button>
                                        </div>
                                        {#if selectedMaterialDesc}<p class="text-[11px] text-blue-600 font-medium px-1">{selectedMaterialDesc}</p>{/if}
                                    </div>
                                </div>

                                <div class="grid grid-cols-1 md:grid-cols-12 gap-6">
                                    <div class="md:col-span-6 space-y-2">
                                        <Label for="country">País Origen (ISO)</Label>
                                        <div class="flex gap-2">
                                            <div class="relative w-full">
                                                <Globe class="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                                                <Input id="country" bind:value={selectedCountryName} readonly onclick={() => showCountryModal = true} class="pl-9 cursor-pointer" placeholder="Seleccione..."/>
                                            </div>
                                            <Button variant="outline" size="icon" type="button" onclick={() => showCountryModal = true} class="shrink-0"><FolderSearch class="h-4 w-4" /></Button>
                                        </div>
                                    </div>

                                    <div class="md:col-span-6 space-y-2">
                                        <Label for="uom" class="required">Unidad de Medida (TIGIE)</Label>
                                        <div class="flex gap-2">
                                            <div class="relative w-full">
                                                <Scale class="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                                                <Input id="uom" bind:value={formData.unit_of_measure} placeholder="Seleccione..." class="pl-9 font-mono cursor-pointer" readonly onclick={() => showUOMModal = true}/>
                                            </div>
                                            <Button variant="outline" size="icon" type="button" onclick={() => showUOMModal = true} class="shrink-0"><FolderSearch class="h-4 w-4" /></Button>
                                        </div>
                                    </div>
                                </div>

                                <div class="p-5 border rounded-xl bg-slate-50 dark:bg-slate-900/30 space-y-6">
                                    <h3 class="font-medium text-sm text-green-700 dark:text-green-400 flex items-center gap-2">
                                        <DollarSign class="h-4 w-4"/> Costos y Valor Agregado
                                    </h3>
                                    
                                    <div class="grid grid-cols-1 md:grid-cols-12 gap-6">
                                        <div class="md:col-span-4 space-y-2">
                                            <Label for="unit_cost">Costo Unitario</Label>
                                            <div class="relative">
                                                <span class="absolute left-3 top-2.5 text-muted-foreground font-semibold">$</span>
                                                <Input type="number" step="0.0001" id="unit_cost" bind:value={formData.unit_cost} class="pl-7 bg-background" />
                                            </div>
                                        </div>

                                        <div class="md:col-span-4 space-y-2">
                                            <Label for="unit_weight">Peso Unitario</Label>
                                            <div class="flex gap-2">
                                                <Input type="number" step="0.0001" id="unit_weight" bind:value={formData.unit_weight} placeholder="0.0000" class="bg-background"/>
                                                <Select.Root type="single" value={formData.weight_type} onValueChange={(v) => formData.weight_type = v}>
                                                    <Select.Trigger class="w-[90px] bg-background">{formData.weight_type}</Select.Trigger>
                                                    <Select.Content>
                                                        <Select.Item value="KG">KG</Select.Item>
                                                        <Select.Item value="LB">LB</Select.Item>
                                                    </Select.Content>
                                                </Select.Root>
                                            </div>
                                        </div>

                                        <div class="md:col-span-4 space-y-2">
                                            <Label>Moneda</Label>
                                            <div class="flex flex-col gap-2">
                                                <div class="flex gap-4">
                                                    <label class="text-xs flex items-center gap-2 cursor-pointer">
                                                        <input type="radio" name="inv_currency_type" value="NA" bind:group={formData.currency_type} class="accent-green-600" /> Nacional
                                                    </label>
                                                    <label class="text-xs flex items-center gap-2 cursor-pointer">
                                                        <input type="radio" name="inv_currency_type" value="EX" bind:group={formData.currency_type} class="accent-green-600" /> Extranjera
                                                    </label>
                                                </div>
                                                <Button variant="outline" size="sm" type="button" onclick={() => { formData.currency_type = 'CATALOG'; showCurrencyModal = true; }} class="w-full justify-between bg-background">
                                                    <span class="flex items-center gap-2 text-xs"><FolderSearch class="h-3 w-3" /> {selectedCurrencyName || 'Catálogo'}</span>
                                                </Button>
                                            </div>
                                        </div>
                                    </div>

                                    <Separator class="bg-border/60" />

                                    <div class="grid grid-cols-1 md:grid-cols-12 gap-6">
                                        <div class="md:col-span-8 space-y-3">
                                            <Label class="font-semibold text-xs uppercase tracking-wider text-muted-foreground">Tipo Valor Agregado</Label>
                                            <div class="flex flex-wrap gap-6 pt-1">
                                                <div class="flex items-center space-x-2 bg-background px-3 py-1.5 rounded-md border shadow-sm">
                                                    <input type="radio" id="va_ext" name="va_type" value="USD" bind:group={formData.value_added_type} class="accent-primary h-4 w-4 cursor-pointer" />
                                                    <Label for="va_ext" class="font-normal cursor-pointer text-sm">Extranjera (Dls)</Label>
                                                </div>
                                                <div class="flex items-center space-x-2 bg-background px-3 py-1.5 rounded-md border shadow-sm">
                                                    <input type="radio" id="va_nac" name="va_type" value="MXN" bind:group={formData.value_added_type} class="accent-primary h-4 w-4 cursor-pointer" />
                                                    <Label for="va_nac" class="font-normal cursor-pointer text-sm">Nacional (Pesos)</Label>
                                                </div>
                                                <div class="flex items-center space-x-2 bg-background px-3 py-1.5 rounded-md border shadow-sm">
                                                    <input type="radio" id="va_pct" name="va_type" value="PERCENT" bind:group={formData.value_added_type} class="accent-primary h-4 w-4 cursor-pointer" />
                                                    <Label for="va_pct" class="font-normal cursor-pointer text-sm">Porcentaje</Label>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="md:col-span-4 space-y-2">
                                            <Label for="added_value">Valor / Porcentaje</Label>
                                            <div class="relative">
                                                {#if formData.value_added_type === 'PERCENT'}
                                                    <span class="absolute right-3 top-2.5 text-muted-foreground font-bold">%</span>
                                                {:else}
                                                    <span class="absolute left-3 top-2.5 text-muted-foreground font-semibold">$</span>
                                                {/if}
                                                <Input type="number" step="0.0001" id="added_value" bind:value={formData.added_value} class="{formData.value_added_type === 'PERCENT' ? 'pr-8' : 'pl-7'} bg-background" placeholder="0.00"/>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="grid grid-cols-1 md:grid-cols-12 gap-6 pt-4 border-t">
                                    <div class="md:col-span-6 space-y-2">
                                        <Label for="frac_us">Fracción Americana (HTS)</Label>
                                        <div class="flex gap-2">
                                            <Input id="frac_us" bind:value={formData.us_fraction} maxlength={16} placeholder="Ej: 8501.10.00" class="font-mono cursor-pointer" readonly onclick={() => showUSFractionModal = true}/>
                                            <Button variant="outline" size="icon" type="button" onclick={() => showUSFractionModal = true} class="shrink-0"><FolderSearch class="h-4 w-4" /></Button>
                                        </div>
                                    </div>
                                </div>

                            </Tabs.Content>

                            <Tabs.Content value="opciones" class="space-y-6 pt-6 animate-in fade-in duration-300">
                                <div class="p-6 border rounded-xl space-y-6">
                                    <h3 class="font-medium text-sm text-muted-foreground">Configuración General</h3>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                                        <div class="space-y-2">
                                            <Label for="fcc">Clave FCC</Label>
                                            <Input id="fcc" bind:value={formData.fcc_key} maxlength={30} />
                                        </div>
                                        <div class="space-y-2">
                                            <Label for="supplier">Proveedor (Textil)</Label>
                                            <Input id="supplier" bind:value={formData.supplier} maxlength={14} />
                                        </div>
                                    </div>
                                    <div class="space-y-2">
                                        <Label for="photo" class="flex items-center gap-2"><ImageIcon class="h-4 w-4"/> URL Imagen de la parte</Label>
                                        <Input id="photo" bind:value={formData.part_photo} maxlength={255} placeholder="https://..." />
                                    </div>
                                </div>
                            </Tabs.Content>

                            <Tabs.Content value="opcionales2" class="space-y-6 pt-6 animate-in fade-in duration-300">
                                <div class="p-6 border rounded-xl space-y-4">
                                    <h3 class="font-medium text-sm text-muted-foreground">Regulaciones Sanitarias</h3>
                                    <div class="grid grid-cols-1 md:grid-cols-2">
                                        <div class="space-y-2">
                                            <Label for="fda">Clave FDA</Label>
                                            <Input id="fda" bind:value={formData.fda_key} maxlength={20} />
                                        </div>
                                    </div>
                                </div>
                            </Tabs.Content>

                            <Tabs.Content value="otros" class="space-y-6 pt-6 animate-in fade-in duration-300">
                                <div class="grid grid-cols-1 md:grid-cols-12 gap-8">
                                    
                                    <div class="md:col-span-6 space-y-6">
                                        <div class="space-y-2">
                                            <Label for="client_id" class="required">Cliente Asignado</Label>
                                            <div class="flex gap-2">
                                                <div class="relative w-full">
                                                    <UserCheck class="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                                                    <Input id="client_id" bind:value={selectedClientName} class="pl-9 cursor-pointer" placeholder="Seleccione un cliente..." readonly onclick={() => showClientModal = true}/>
                                                </div>
                                                <Button variant="outline" class="shrink-0" type="button" onclick={() => showClientModal = true}><FolderSearch class="h-4 w-4 mr-2" /> Buscar</Button>
                                            </div>
                                            {#if selectedClientName}
                                                <div class="flex items-center gap-2 text-xs pt-1">
                                                    {#if selectedClientStatus}<span class="text-green-600 flex items-center gap-1 font-medium"><CheckCircle2 class="h-3 w-3"/> Cliente Activo</span>{:else}<span class="text-red-600 flex items-center gap-1 font-medium"><XCircle class="h-3 w-3"/> Cliente Inactivo</span>{/if}
                                                </div>
                                            {/if}
                                        </div>

                                        <div class="space-y-2">
                                            <Label for="comm_pn">Número de Parte Comercial</Label>
                                            <Input id="comm_pn" bind:value={formData.commercial_part_number} maxlength={70} />
                                        </div>

                                        <div class="p-4 border rounded-xl space-y-3 bg-muted/20">
                                            <Label for="alt_um" class="flex items-center gap-2"><Scale class="h-4 w-4"/> UM Conversión (Alterna)</Label>
                                            <div class="flex gap-2">
                                                <Input id="alt_um" bind:value={formData.alternate_unit_measure} placeholder="Seleccione..." class="font-mono cursor-pointer" readonly onclick={() => showAltUOMModal = true}/>
                                                <Button variant="outline" size="icon" type="button" onclick={() => showAltUOMModal = true} class="shrink-0"><FolderSearch class="h-4 w-4" /></Button>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="md:col-span-6 space-y-6">
                                        <div class="p-6 border rounded-xl space-y-4 bg-slate-50 dark:bg-slate-900/30">
                                            <h3 class="font-medium text-sm text-muted-foreground">Datos Regulatorios Adicionales</h3>
                                            
                                            <div class="space-y-4">
                                                <div class="space-y-2">
                                                    <Label for="fraction_mx" class="required">Fracción Arancelaria (MX)</Label>
                                                    <div class="flex gap-2">
                                                        <Input id="fraction_mx" bind:value={formData.fraction} readonly onclick={() => showFractionModal = true} class="cursor-pointer font-mono" placeholder="Seleccione..."/>
                                                        <Button variant="outline" size="icon" type="button" onclick={() => showFractionModal = true} class="shrink-0"><FolderSearch class="h-4 w-4" /></Button>
                                                    </div>
                                                </div>

                                                <div class="grid grid-cols-2 gap-4">
                                                    <div class="space-y-2">
                                                        <Label for="eccn">ECCN</Label>
                                                        <Input id="eccn" bind:value={formData.eccn} maxlength={20} class="font-mono"/>
                                                    </div>
                                                    <div class="space-y-2">
                                                        <Label for="lic_code">License Code</Label>
                                                        <Input id="lic_code" bind:value={formData.license_code} maxlength={3} class="font-mono"/>
                                                    </div>
                                                </div>

                                                <div class="grid grid-cols-2 gap-4">
                                                    <div class="space-y-2">
                                                        <Label for="exp_code">Export Code</Label>
                                                        <Input id="exp_code" bind:value={formData.export_code} maxlength={2} class="font-mono"/>
                                                    </div>
                                                    <div class="space-y-2">
                                                        <Label for="exc_sym">Símbolo Exclusión</Label>
                                                        <Input id="exc_sym" bind:value={formData.exclusion_symbol} maxlength={19} />
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="flex items-center gap-3 p-4 border rounded-xl">
                                            <Switch id="is_active" bind:checked={formData.is_active} disabled={loading} />
                                            <Label for="is_active" class="cursor-pointer">Parte Activa en Sistema</Label>
                                        </div>
                                    </div>

                                </div>
                            </Tabs.Content>
                        </div>

                    </Tabs.Root>
                </Card.Content>
            </Card.Root>
        </form>
    {/if}
    </div>
</div>

<div class="fixed bottom-0 left-0 right-0 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 border-t shadow-lg z-[5] group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] ml-[calc(var(--sidebar-width))]">
    <div class="px-4 py-4 space-y-4 max-w-[1400px] mx-auto">
        <Tabs.Root bind:value={activeTab}>
            <div class="w-full overflow-x-auto pb-2">
                {#if formType === 'fa'}
                    <Tabs.List class="inline-flex md:grid md:w-full md:grid-cols-3">
                        <Tabs.Trigger value="general" class="whitespace-nowrap">
                            <Package size={16} class="mr-2" />
                            General
                        </Tabs.Trigger>
                        <Tabs.Trigger value="cont1" class="whitespace-nowrap">
                            <FileText size={16} class="mr-2" />
                            Continuación 1
                        </Tabs.Trigger>
                        <Tabs.Trigger value="cont2" class="whitespace-nowrap">
                            <Settings size={16} class="mr-2" />
                            Continuación 2
                        </Tabs.Trigger>
                    </Tabs.List>
                {:else}
                    <Tabs.List class="inline-flex md:grid md:w-full md:grid-cols-4">
                        <Tabs.Trigger value="general" class="whitespace-nowrap">
                            <Package size={16} class="mr-2" />
                            General
                        </Tabs.Trigger>
                        <Tabs.Trigger value="opciones" class="whitespace-nowrap">
                            <Settings size={16} class="mr-2" />
                            Opciones
                        </Tabs.Trigger>
                        <Tabs.Trigger value="opcionales2" class="whitespace-nowrap">
                            <FileText size={16} class="mr-2" />
                            Opcionales 2
                        </Tabs.Trigger>
                        <Tabs.Trigger value="otros" class="whitespace-nowrap">
                            <DollarSign size={16} class="mr-2" />
                            Otros
                        </Tabs.Trigger>
                    </Tabs.List>
                {/if}
            </div>
        </Tabs.Root>

        <div class="flex justify-end gap-3">
            <Button type="button" variant="outline" href="/dashboard/goods/parts" disabled={loading}>
                Cancelar
            </Button>
            <Button type="button" onclick={handleSubmit} disabled={loading}>
                {#if loading}
                    <LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
                    Guardando...
                {:else}
                    <Save size={16} class="mr-2" />
                    {isEdit ? 'Actualizar' : 'Guardar'}
                {/if}
            </Button>
        </div>
    </div>
</div>

<ClientSelectorDialog bind:open={showClientModal} onSelect={handleClientSelect} />
<ClassSelectorDialog bind:open={showClassModal} onSelect={handleClassSelect} />
<MaterialTypeSelectorDialog bind:open={showMaterialModal} onSelect={handleMaterialSelect} />
<UnitMeasureSelectorDialog bind:open={showUOMModal} onSelect={handleUOMSelect} />
<UnitMeasureSelectorDialog bind:open={showAltUOMModal} onSelect={handleAltUOMSelect} />
<CurrencySelectorDialog bind:open={showCurrencyModal} onSelect={handleCurrencySelect} />
<CountrySelectorDialog bind:open={showCountryModal} onSelect={handleCountrySelect} />
<FractionSelectorDialog bind:open={showFractionModal} onSelect={handleFractionSelect} />
<USFractionSelectorDialog bind:open={showUSFractionModal} onSelect={handleUSFractionSelect} />

<style>
    :global(.required::after) {
        content: " *";
        color: hsl(var(--destructive));
    }
</style>