<script lang="ts">
	import * as Tabs from '$lib/components/ui/tabs';
	import * as Card from '$lib/components/ui/card';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Button } from '$lib/components/ui/button';
	import * as Table from '$lib/components/ui/table';
	import {
		Search,
		Save,
		Package,
		ListChecks,
		FileText,
		Plus,
		Pencil,
		Trash2,
		TableProperties,
		Check,
		X
	} from 'lucide-svelte';
	import { onMount } from 'svelte';
	import { page } from '$app/stores';
	import { toast } from 'svelte-sonner';
	import { goto } from '$app/navigation';
	import { companyStore } from '$lib/stores/company.svelte';
	import CountrySelectorDialog from '$lib/components/dashboard/goods/modales/country-selector-dialog.svelte';
	import type { Country } from '$lib/api/dashboard/reference_data/countries';

	// Variables para controlar el estado de los modales
	let dialogFda04Open = $state(false);
	let dialogFda23Open = $state(false);
	let dialogFda25Open = $state(false);
	let countryModalOpen = $state(false);

	let globalFdaCode = $state('');
	let globalFdaId = $state<number | null>(null);
	let isLoadingFda = $state(false);
	let isSaving = $state(false);

	let formData = $state({
		description: '',
		fda_code: '',
		requirements: '',
		manufacturer_number: '',
		country_of_production: '',
		storage_status: '',
		warehouse_code: '',
		call_atl: ''
	});

	let fda01Data = $state<any>({
		prod_code: '',
		commodity_desc: '',
		brand_name: '',
		disclaimer: '',
		pgm_code: '',
		proc_code: '',
		intnd_use_code: '',
		intnd_use_desc: '',
		temp_qual: '',
		temp_type: '',
		temp_degrees: 0,
		temp_negative: 0,
		temp_location: '',
		quantity_1: 0,
		qty_uom_1: '',
		quantity_2: 0,
		qty_uom_2: '',
		quantity_3: 0,
		qty_uom_3: '',
		ctry_prod: '',
		ctry_source: '',
		ctry_growth: '',
		ctry_refusal: '',
		ctry_shipping: '',
		manuf_key: '',
		shipper_key: '',
		ult_cons_key: '',
		fda_imp_key: '',
		pn_subm_key: '',
		consol_key: '',
		producer_key: '',
		owner_key: '',
		deli_party_key: '',
		grower_key: '',
		dev_ini_imp_key: '',
		lacf_cont_1: '',
		lacf_cont_2: '',
		lacf_cont_3: '',
		pn_transmitter_key: ''
	});

	let fda23Codes = $state<any[]>([
		{ line: 1, aoc_code: '', aoc_qual: '' },
		{ line: 2, aoc_code: '', aoc_qual: '' },
		{ line: 3, aoc_code: '', aoc_qual: '' },
		{ line: 4, aoc_code: '', aoc_qual: '' },
		{ line: 5, aoc_code: '', aoc_qual: '' }
	]);
	let currentFda23 = $state<any>({
		line: 1,
		aoc_code: '',
		aoc_qual: ''
	});
	let editIndexFda23 = $state<number | null>(null);

	let fda04Data = $state<any[]>([]);
	let currentFda04 = $state<any>({
		line: 1,
		ele_name: '',
		ele_qty: 0,
		ele_qty_uom: '',
		ele_pctg: 0
	});
	let editIndexFda04 = $state<number | null>(null);

	let fda25Data = $state<any[]>([]);
	let currentFda25 = $state<any>({
		line: 1,
		lot_number: '',
		prod_start_date: '',
		prod_end_date: ''
	});
	let editIndexFda25 = $state<number | null>(null);

	// Utilities para modals FDA04
	function openNewFda04() {
		currentFda04 = {
			line: fda04Data.length + 1,
			ele_name: '',
			ele_qty: 0,
			ele_qty_uom: '',
			ele_pctg: 0
		};
		editIndexFda04 = null;
		dialogFda04Open = true;
	}
	function editFda04(idx: number) {
		currentFda04 = { ...fda04Data[idx] };
		editIndexFda04 = idx;
		dialogFda04Open = true;
	}
	function saveFda04() {
		if (!currentFda04.ele_name) {
			toast.error('Ele Name es obligatorio');
			return;
		}
		if (editIndexFda04 !== null) fda04Data[editIndexFda04] = { ...currentFda04 };
		else fda04Data.push({ ...currentFda04 });

		dialogFda04Open = false;
	}
	function removeFda04(idx: number) {
		fda04Data.splice(idx, 1);
		// Reindexar line numbers
		fda04Data.forEach((item, i) => (item.line = i + 1));
	}

	// Utilities para modals FDA23
	function openNewFda23() {
		currentFda23 = {
			line: fda23Codes.length + 1,
			aoc_code: '',
			aoc_qual: ''
		};
		editIndexFda23 = null;
		dialogFda23Open = true;
	}
	function editFda23(idx: number) {
		currentFda23 = { ...fda23Codes[idx] };
		editIndexFda23 = idx;
		dialogFda23Open = true;
	}
	function saveFda23() {
		if (!currentFda23.aoc_code) {
			toast.error('AOC Code es obligatorio');
			return;
		}
		if (editIndexFda23 !== null) {
			// Si el índice es < 5 y estamos editando un slot existente, lo sobreescribimos
			fda23Codes[editIndexFda23] = { ...currentFda23 };
		} else {
			// Si es nuevo, buscamos el primer slot vacío entre los 5 primeros o agregamos
			let emptyIdx = fda23Codes.findIndex((c, i) => i < 5 && !c.aoc_code && !c.aoc_qual);
			if (emptyIdx !== -1) {
				fda23Codes[emptyIdx] = { ...currentFda23, line: emptyIdx + 1 };
			} else {
				fda23Codes.push({ ...currentFda23, line: fda23Codes.length + 1 });
			}
		}

		dialogFda23Open = false;
	}
	function removeFda23(idx: number) {
		if (idx < 5) {
			// No eliminamos los 5 primeros slots, solo los limpiamos
			fda23Codes[idx] = { line: idx + 1, aoc_code: '', aoc_qual: '' };
		} else {
			fda23Codes.splice(idx, 1);
			// Reindexar solo los que están después del 5
			fda23Codes.forEach((item, i) => (item.line = i + 1));
		}
	}

	// Utilities para modals FDA25
	function openNewFda25() {
		currentFda25 = {
			line: fda25Data.length + 1,
			lot_number: '',
			prod_start_date: '',
			prod_end_date: ''
		};
		editIndexFda25 = null;
		dialogFda25Open = true;
	}
	function editFda25(idx: number) {
		currentFda25 = { ...fda25Data[idx] };
		editIndexFda25 = idx;
		dialogFda25Open = true;
	}
	function saveFda25() {
		if (!currentFda25.lot_number) {
			toast.error('Lot Number es obligatorio');
			return;
		}
		if (editIndexFda25 !== null) fda25Data[editIndexFda25] = { ...currentFda25 };
		else fda25Data.push({ ...currentFda25 });

		dialogFda25Open = false;
	}
	function removeFda25(idx: number) {
		fda25Data.splice(idx, 1);
		// Reindexar
		fda25Data.forEach((item, i) => (item.line = i + 1));
	}

	onMount(() => {
		const pageId = $page.params.id;
		if (pageId && pageId !== 'new') {
			// Asumiremos que tenemos el ID o podemos recuperar datos por ID.
			// Por ahora solo asiganmos el estado
			globalFdaId = Number(pageId);
			// Recuperar datos desde el backend si venimos a editar
			loadFdaDataById(globalFdaId);
		}
	});

	// Función para cargar los datos de un FDA por ID
	async function loadFdaDataById(id: number) {
		isLoadingFda = true;
		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) return;

			const res = await fetch(`/api-sveltekit/fda-catalog/${id}?company_id=${companyId}`);
			if (res.ok) {
				const fda = await res.json();
				if (fda) {
					globalFdaCode = fda.fda_key;
					formData.description = fda.description || '';
					formData.fda_code = fda.fda_code || '';
					formData.requirements = fda.requirements || '';
					formData.manufacturer_number = fda.manufacturer_number || '';
					formData.country_of_production = fda.country_of_production || '';
					formData.storage_status = fda.storage_status || '';
					formData.warehouse_code = fda.warehouse_code || '';
					formData.call_atl = fda.call_atl || '';
				}

				// Fetch FDA01
				const specRes = await fetch(
					`/api-sveltekit/fda-catalog/${id}/specifications?company_id=${companyId}`
				);
				if (specRes.ok) {
					const specs = await specRes.json();
					if (specs) Object.assign(fda01Data, specs);
				}

				// Fetch FDA23
				const affRes = await fetch(
					`/api-sveltekit/fda-catalog/${id}/affirmation-codes?company_id=${companyId}`
				);
				if (affRes.ok) {
					const aff = await affRes.json();
					if (aff && Array.isArray(aff)) {
						if (aff.length > 0) {
							// Cargamos todos los que vengan
							fda23Codes = aff.map((item: any, idx: number) => ({ ...item }));
							// Pero nos aseguramos de que haya al menos 5 slots para la pestaña General
							while (fda23Codes.length < 5) {
								fda23Codes.push({ line: fda23Codes.length + 1, aoc_code: '', aoc_qual: '' });
							}
						}
					}
				}
				// Fetch FDA04 Consituent Elements
				const constRes = await fetch(
					`/api-sveltekit/fda-catalog/${id}/constituent-elements?company_id=${companyId}`
				);
				if (constRes.ok) {
					const f04 = await constRes.json();
					if (f04 && Array.isArray(f04)) fda04Data = f04;
				}

				// Fetch FDA25 Lot Productions
				const lotRes = await fetch(
					`/api-sveltekit/fda-catalog/${id}/lot-productions?company_id=${companyId}`
				);
				if (lotRes.ok) {
					const f25 = await lotRes.json();
					if (f25 && Array.isArray(f25)) {
						fda25Data = f25.map((lot: any) => ({
							...lot,
							prod_start_date: lot.production_start_date,
							prod_end_date: lot.production_end_date
						}));
					}
				}
			}
		} catch (error) {
			console.error('Error cargando FDA:', error);
			toast.error('Error al cargar datos');
		} finally {
			isLoadingFda = false;
		}
	}

	// Función para buscar una Clave FDA
	async function searchFdaCode() {
		if (!globalFdaCode.trim()) return;

		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;

		isLoadingFda = true;
		try {
			const res = await fetch(
				`/api-sveltekit/fda-catalog?search=${encodeURIComponent(globalFdaCode)}&company_id=${companyId}`
			);
			if (res.ok) {
				const data = await res.json();
				if (data.items && data.items.length > 0) {
					// Asumimos que toma el primer resultado que coincida
					const fda = data.items[0];
					globalFdaId = fda.id;
					// Idealmente aquí también cargaríamos details como FDA01, FDA04, etc.
				} else {
					globalFdaId = null;
					// Limpiar formulario si es nuevo registro
					formData.description = '';
					formData.fda_code = '';
					formData.requirements = '';
					formData.manufacturer_number = '';
					formData.country_of_production = '';
					formData.storage_status = '';
				}
			}
		} catch (error) {
			console.error('Error buscando FDA Code:', error);
		} finally {
			isLoadingFda = false;
		}
	}

	async function saveFdaData() {
		if (!globalFdaCode.trim()) {
			toast.error('La Clave FDA es obligatoria');
			return;
		}
		if (!formData.description.trim()) {
			toast.error('La Descripción es obligatoria');
			return;
		}

		const companyId = companyStore.activeCompany?.id;
		if (!companyId) {
			toast.error('Compañía no seleccionada');
			return;
		}

		isSaving = true;
		try {
			const payload = {
				fda_key: globalFdaCode,
				description: formData.description,
				fda_code: formData.fda_code || null,
				requirements: formData.requirements || null,
				manufacturer_number: formData.manufacturer_number || null,
				country_of_production: formData.country_of_production || null,
				storage_status: formData.storage_status || null,
				warehouse_code: formData.warehouse_code || null,
				call_atl: formData.call_atl || null,
				fda01: fda01Data,
				fda23_codes: fda23Codes.filter((c) => c.aoc_code.trim() !== ''),
				fda04_elements: fda04Data.map((ele) => ({
					...ele,
					ele_qty:
						ele.ele_qty === '' || ele.ele_qty === undefined || ele.ele_qty === null
							? null
							: parseFloat(ele.ele_qty),
					ele_pctg:
						ele.ele_pctg === '' || ele.ele_pctg === undefined || ele.ele_pctg === null
							? null
							: parseFloat(ele.ele_pctg)
				})),
				fda25_lots: fda25Data.map((lot) => ({
					...lot,
					production_start_date: lot.prod_start_date || null,
					production_end_date: lot.prod_end_date || null
				}))
			};

			let url = `/api-sveltekit/fda-catalog?company_id=${companyId}`;
			let method = 'POST';

			if (globalFdaId) {
				url += `&id=${globalFdaId}`;
				method = 'PUT';
			}

			const res = await fetch(url, {
				method,
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify(payload)
			});

			const data = await res.json();

			if (res.ok) {
				toast.success(
					globalFdaId ? 'Registro actualizado correctamente' : 'Registro creado correctamente'
				);
				if (!globalFdaId) {
					globalFdaId = data.id;
				}
				// Redirigir a la lista despues de guardar
				setTimeout(() => {
					goto('/dashboard/goods/fda-codes');
				}, 1000);
			} else {
				toast.error(data.error || 'Error al guardar el registro');
			}
		} catch (error) {
			console.error('Error saving FDA Code:', error);
			toast.error('Ocurrió un error inesperado al guardar');
		} finally {
			isSaving = false;
		}
	}
</script>

<Tabs.Root value="general" class="flex h-[calc(100vh-4rem)] flex-col">
	<div class="flex flex-1 flex-col gap-4 overflow-auto p-4 pb-28">
		<div class="flex flex-col gap-1">
			<h1 class="text-2xl font-bold">CÓDIGOS F.D.A. / FDA CODES</h1>
			<p class="text-sm text-muted-foreground">
				Gestión de códigos FDA para mercancías / FDA goods code management
			</p>
		</div>

		<div class="flex flex-wrap items-center gap-3 rounded-lg border bg-muted/20 p-4 shadow-sm">
			<Label for="global-clave-fda" class="required text-base font-semibold whitespace-nowrap">
				Clave FDA
			</Label>
			<div class="relative flex w-full max-w-[250px] items-center gap-2">
				<div class="relative flex-1">
					<Package class="absolute top-2.5 left-3 h-5 w-5 text-muted-foreground" />
					<Input
						id="global-clave-fda"
						bind:value={globalFdaCode}
						placeholder="Ingrese Código F.D.A"
						class="bg-background pl-10 font-mono text-lg font-bold text-foreground uppercase"
						onkeydown={(e) => e.key === 'Enter' && searchFdaCode()}
					/>
				</div>
				<Button variant="outline" size="icon" onclick={searchFdaCode} disabled={isLoadingFda}>
					<Search class="h-4 w-4" />
				</Button>
			</div>
			<span class="flex items-center gap-2 text-sm text-muted-foreground">
				(Packet Code)
				{#if globalFdaId}
					<span
						class="inline-flex items-center rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-green-600/20 ring-inset"
						>Registrado</span
					>
				{:else if globalFdaCode && !isLoadingFda && globalFdaId === null}
					<span
						class="inline-flex items-center rounded-md bg-yellow-50 px-2 py-1 text-xs font-medium text-yellow-800 ring-1 ring-yellow-600/20 ring-inset"
						>Nuevo registro</span
					>
				{/if}
			</span>
		</div>

		<Tabs.Content value="general" class="mt-2 flex-1">
			<div class="mx-auto flex w-full flex-col gap-6">
				<Card.Root class="shadow-sm">
					<Card.Content class="space-y-8 p-6">
						<div class="grid grid-cols-1 gap-x-6 gap-y-6">
							<div class="space-y-2">
								<Label for="descripcion" class="flex items-center gap-1">Descripción</Label>
								<Input id="descripcion" bind:value={formData.description} />
								<p class="text-[11px] text-muted-foreground">(Description)</p>
							</div>
						</div>

						<div class="space-y-6 rounded-xl border bg-muted/40 p-5 dark:bg-muted/10">
							<h3 class="flex items-center gap-2 text-sm font-medium text-muted-foreground">
								<FileText class="h-4 w-4" /> Especificaciones del Producto FDA
							</h3>

							<div class="grid grid-cols-1 gap-x-6 gap-y-4 md:grid-cols-2">
								<div class="space-y-2">
									<Label for="codigo-producto">Código FDA del producto</Label>
									<Input id="codigo-producto" bind:value={formData.fda_code} />
									<p class="text-[11px] text-muted-foreground">(Product Code)</p>
								</div>

								<div class="space-y-2">
									<Label for="estatus-almacenamiento">Estatus de Almacenamientos</Label>
									<Input id="estatus-almacenamiento" bind:value={formData.storage_status} />
									<p class="text-[11px] text-muted-foreground">(Cargo Storage Status)</p>
								</div>

								<div class="space-y-2">
									<Label for="requerimientos">Requerimientos</Label>
									<Input id="requerimientos" bind:value={formData.requirements} />
									<p class="text-[11px] text-muted-foreground">(Requirement)</p>
								</div>

								<div class="space-y-2">
									<Label for="numero-fabricante">Número de Fabricante</Label>
									<Input id="numero-fabricante" bind:value={formData.manufacturer_number} />
									<p class="text-[11px] text-muted-foreground">(Manufacture)</p>
								</div>

								<div class="space-y-2">
									<Label for="pais-produccion">País de Producción</Label>
									<div class="flex gap-2">
										<Input
											id="pais-produccion"
											class="font-mono"
											bind:value={formData.country_of_production}
										/>
										<Button
											variant="outline"
											size="icon"
											type="button"
											class="shrink-0"
											onclick={() => (countryModalOpen = true)}
										>
											<Search class="h-4 w-4" />
										</Button>
									</div>
									<p class="text-[11px] text-muted-foreground">(Country of Production)</p>
								</div>

								<div class="space-y-2">
									<Label for="warehouse-code">Código de Almacén</Label>
									<Input id="warehouse-code" bind:value={formData.warehouse_code} />
									<p class="text-[11px] text-muted-foreground">(Warehouse Code)</p>
								</div>

								<div class="space-y-2">
									<Label for="call-atl">Call ATL</Label>
									<Input id="call-atl" bind:value={formData.call_atl} />
									<p class="text-[11px] text-muted-foreground">(ATL Call)</p>
								</div>
							</div>
						</div>

						<div class="space-y-6 rounded-xl border bg-muted/40 p-5 dark:bg-muted/10">
							<h3 class="flex items-center gap-2 text-sm font-medium text-foreground">
								<ListChecks class="h-4 w-4" /> Códigos de Afirmación (Affirmation Codes)
							</h3>

							<div class="flex flex-col gap-5 pt-2">
								{#each fda23Codes.slice(0, 5) as code, idx}
									<div class="grid grid-cols-2 gap-4">
										<div class="space-y-1">
											<Label class="text-[10px] text-muted-foreground uppercase">
												AOC {idx + 1}
											</Label>
											<Input
												bind:value={code.aoc_code}
												placeholder="Código"
												class="h-8 font-mono text-xs"
											/>
										</div>
										<div class="space-y-1">
											<Label class="text-[10px] text-muted-foreground uppercase">
												Qual {idx + 1}
											</Label>
											<Input
												bind:value={code.aoc_qual}
												placeholder="Calificador"
												class="h-8 font-mono text-xs"
											/>
										</div>
									</div>
								{/each}
							</div>
						</div>
					</Card.Content>
				</Card.Root>
			</div>
		</Tabs.Content>

		<Tabs.Content value="fda01" class="mt-2 flex-1">
			<div class="mx-auto flex w-full flex-col gap-6">
				<Card.Root class="shadow-sm">
					<Card.Content class="p-6">
						<div class="mb-6 flex items-center gap-2">
							<FileText class="h-5 w-5 text-muted-foreground" />
							<h2 class="text-lg font-semibold">Detalles FDA01</h2>
						</div>

						<div class="grid grid-cols-1 gap-x-6 gap-y-4 md:grid-cols-2 xl:grid-cols-3">
							<div class="space-y-3">
								{#each [{ l: 'Prod Code', k: 'prod_code' }, { l: 'Comodity Desc', k: 'commodity_desc' }, { l: 'Brand Name', k: 'brand_name' }, { l: 'Disclaimer', k: 'disclaimer' }, { l: 'Pgm Code', k: 'pgm_code' }, { l: 'Proc Code', k: 'proc_code' }, { l: 'Intnd Use Code', k: 'intnd_use_code' }, { l: 'Intnd Use Desc', k: 'intnd_use_desc' }, { l: 'Temp Qual', k: 'temp_qual' }, { l: 'Temp Type', k: 'temp_type' }] as { l, k }}
									<div class="grid grid-cols-[110px_1fr] items-center gap-2">
										<Label class="text-right text-xs text-muted-foreground">{l}:</Label>
										<Input class="h-8 text-sm" bind:value={fda01Data[k]} />
									</div>
								{/each}
								{#each [{ l: 'Temp Degrees', k: 'temp_degrees' }, { l: 'Temp Negative', k: 'temp_negative' }] as { l, k }}
									<div class="grid grid-cols-[110px_1fr] items-center gap-2">
										<Label class="text-right text-xs text-muted-foreground">{l}:</Label>
										<Input
											type="number"
											step="0.01"
											class="h-8 text-right font-mono text-sm"
											bind:value={fda01Data[k]}
										/>
									</div>
								{/each}
								<div class="grid grid-cols-[110px_1fr] items-center gap-2">
									<Label class="text-right text-xs text-muted-foreground">Temp Location:</Label>
									<Input class="h-8 text-sm" bind:value={fda01Data.temp_location} />
								</div>
								{#each [{ l: 'Quantity 1', k: 'quantity_1' }, { l: 'Quantity 2', k: 'quantity_2' }] as { l, k }}
									<div class="grid grid-cols-[110px_1fr] items-center gap-2">
										<Label class="text-right text-xs text-muted-foreground">{l}:</Label>
										<Input
											type="number"
											step="0.01"
											class="h-8 text-right font-mono text-sm"
											bind:value={fda01Data[k]}
										/>
									</div>
								{/each}
								<div class="grid grid-cols-[110px_1fr] items-center gap-2">
									<Label class="text-right text-xs text-muted-foreground">Qty Uom 1:</Label>
									<Input class="h-8 text-sm" bind:value={fda01Data.qty_uom_1} />
								</div>
							</div>

							<div class="space-y-3">
								<div class="grid grid-cols-[110px_1fr] items-center gap-2">
									<Label class="text-right text-xs text-muted-foreground">Qty Uom 2:</Label>
									<Input class="h-8 text-sm" bind:value={fda01Data.qty_uom_2} />
								</div>
								<div class="grid grid-cols-[110px_1fr] items-center gap-2">
									<Label class="text-right text-xs text-muted-foreground">Quantity 3:</Label>
									<Input
										type="number"
										step="0.01"
										class="h-8 text-right font-mono text-sm"
										bind:value={fda01Data.quantity_3}
									/>
								</div>
								{#each [{ l: 'Qty Uom 3', k: 'qty_uom_3' }, { l: 'Ctry Prod', k: 'ctry_prod' }, { l: 'Ctry Source', k: 'ctry_source' }, { l: 'Ctry Growth', k: 'ctry_growth' }, { l: 'Ctry Refusal', k: 'ctry_refusal' }, { l: 'Ctry Shipping', k: 'ctry_shipping' }, { l: 'Manuf Key', k: 'manuf_key' }, { l: 'Shipper Key', k: 'shipper_key' }, { l: 'Ult Cons Key', k: 'ult_cons_key' }, { l: 'Fda Imp Key', k: 'fda_imp_key' }, { l: 'Pn Subm Key', k: 'pn_subm_key' }, { l: 'Consol Key', k: 'consol_key' }, { l: 'Producer Key', k: 'producer_key' }, { l: 'Owner Key', k: 'owner_key' }] as { l, k }}
									<div class="grid grid-cols-[110px_1fr] items-center gap-2">
										<Label class="text-right text-xs text-muted-foreground">{l}:</Label>
										<Input class="h-8 text-sm" bind:value={fda01Data[k]} />
									</div>
								{/each}
							</div>

							<div class="space-y-3">
								{#each [{ l: 'Deli Party Key', k: 'deli_party_key' }, { l: 'Grower Key', k: 'grower_key' }, { l: 'Dev Ini Imp Key', k: 'dev_ini_imp_key' }, { l: 'Lacf Cont 1', k: 'lacf_cont_1' }, { l: 'Lacf Cont 2', k: 'lacf_cont_2' }, { l: 'Lacf Cont 3', k: 'lacf_cont_3' }, { l: 'PN Transmitter Key', k: 'pn_transmitter_key' }] as { l, k }}
									<div class="grid grid-cols-[110px_1fr] items-center gap-2">
										<Label class="text-right text-xs text-muted-foreground">{l}:</Label>
										<Input class="h-8 text-sm" bind:value={fda01Data[k]} />
									</div>
								{/each}
							</div>
						</div>
					</Card.Content>
				</Card.Root>
			</div>
		</Tabs.Content>

		<Tabs.Content value="fda04" class="mt-2 flex-1">
			<Card.Root class="flex h-full flex-col shadow-sm">
				<div class="flex items-center gap-2 border-b bg-muted/20 p-4">
					<TableProperties class="h-4 w-4 text-muted-foreground" />
					<h3 class="text-sm font-medium">Registros FDA04</h3>
				</div>
				<div class="flex-1 overflow-auto rounded-md border">
					<Table.Root>
						<Table.Header class="bg-muted/50">
							<Table.Row>
								<Table.Head class="w-[100px]">Línea</Table.Head>
								<Table.Head>Ele Name</Table.Head>
								<Table.Head>Ele Qty</Table.Head>
								<Table.Head>Ele Qty UOM</Table.Head>
								<Table.Head>Ele Pctg</Table.Head>
								<Table.Head class="w-[100px] text-right">Acciones</Table.Head>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{#each fda04Data as row, idx (idx)}
								<Table.Row>
									<Table.Cell class="font-medium">{row.line}</Table.Cell>
									<Table.Cell>{row.ele_name}</Table.Cell>
									<Table.Cell>{row.ele_qty || '-'}</Table.Cell>
									<Table.Cell>{row.ele_qty_uom || '-'}</Table.Cell>
									<Table.Cell>{row.ele_pctg || '-'}</Table.Cell>
									<Table.Cell class="text-right">
										<Button variant="ghost" size="icon" onclick={() => editFda04(idx)}>
											<Pencil class="h-4 w-4" />
										</Button>
										<Button
											variant="ghost"
											size="icon"
											class="text-destructive"
											onclick={() => removeFda04(idx)}
										>
											<Trash2 class="h-4 w-4" />
										</Button>
									</Table.Cell>
								</Table.Row>
							{/each}
							{#if fda04Data.length === 0}
								<Table.Row>
									<Table.Cell colspan={6} class="py-6 text-center text-muted-foreground"
										>Sin registros</Table.Cell
									>
								</Table.Row>
							{/if}
						</Table.Body>
					</Table.Root>
				</div>
				<div class="flex justify-end gap-2 border-t bg-muted/10 p-4">
					<Button variant="outline" size="sm" class="gap-2" onclick={openNewFda04}>
						<Plus class="h-4 w-4" /> Insertar
					</Button>

					<Dialog.Root bind:open={dialogFda04Open}>
						<Dialog.Content class="sm:max-w-[425px]">
							<Dialog.Header>
								<Dialog.Title>Constituent Elements</Dialog.Title>
								<Dialog.Description>
									Agrega o edita los elementos para la clave FDA.
								</Dialog.Description>
							</Dialog.Header>

							<div class="grid gap-4 py-4">
								<div class="grid grid-cols-2 gap-4">
									<div class="space-y-2">
										<Label class="text-xs text-muted-foreground">Clave FDA</Label>
										<div class="font-mono text-sm font-medium">{globalFdaCode || '---'}</div>
									</div>
									<div class="space-y-2">
										<Label for="fda04-linea">Línea</Label>
										<Input id="fda04-linea" disabled value={currentFda04.line} class="font-mono" />
									</div>
								</div>

								<div class="space-y-2">
									<Label for="fda04-elename">Ele Name</Label>
									<Input id="fda04-elename" bind:value={currentFda04.ele_name} />
								</div>

								<div class="grid grid-cols-3 gap-4">
									<div class="space-y-2">
										<Label for="fda04-eleqty" class="text-xs">Ele Qty</Label>
										<Input
											type="number"
											step="0.01"
											id="fda04-eleqty"
											bind:value={currentFda04.ele_qty}
											class="text-right font-mono"
										/>
									</div>
									<div class="space-y-2">
										<Label for="fda04-eleuom" class="text-xs">Ele Qty Uom</Label>
										<Input id="fda04-eleuom" bind:value={currentFda04.ele_qty_uom} />
									</div>
									<div class="space-y-2">
										<Label for="fda04-elepctg" class="text-xs">Ele Pctg</Label>
										<Input
											type="number"
											step="0.01"
											id="fda04-elepctg"
											bind:value={currentFda04.ele_pctg}
											class="text-right font-mono"
										/>
									</div>
								</div>
							</div>

							<Dialog.Footer>
								<Button type="button" variant="outline" onclick={() => (dialogFda04Open = false)}>
									Cancelar
								</Button>
								<Button type="button" onclick={saveFda04}>Guardar Elemento</Button>
							</Dialog.Footer>
						</Dialog.Content>
					</Dialog.Root>
				</div>
			</Card.Root>
		</Tabs.Content>

		<Tabs.Content value="fda25" class="mt-2 flex-1">
			<Card.Root class="flex h-full flex-col shadow-sm">
				<div class="flex items-center gap-2 border-b bg-muted/20 p-4">
					<TableProperties class="h-4 w-4 text-muted-foreground" />
					<h3 class="text-sm font-medium">Registros FDA25</h3>
				</div>
				<div class="flex-1 overflow-auto rounded-md border">
					<Table.Root>
						<Table.Header class="bg-muted/50">
							<Table.Row>
								<Table.Head class="w-[100px]">Línea</Table.Head>
								<Table.Head>Lot Number</Table.Head>
								<Table.Head>Production Start Date</Table.Head>
								<Table.Head>Production End Date</Table.Head>
								<Table.Head class="w-[100px] text-right">Acciones</Table.Head>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{#each fda25Data as row, idx (idx)}
								<Table.Row>
									<Table.Cell class="font-medium">{row.line}</Table.Cell>
									<Table.Cell>{row.lot_number}</Table.Cell>
									<Table.Cell>{row.prod_start_date}</Table.Cell>
									<Table.Cell>{row.prod_end_date}</Table.Cell>
									<Table.Cell class="text-right">
										<Button variant="ghost" size="icon" onclick={() => editFda25(idx)}>
											<Pencil class="h-4 w-4" />
										</Button>
										<Button
											variant="ghost"
											size="icon"
											class="text-destructive"
											onclick={() => removeFda25(idx)}
										>
											<Trash2 class="h-4 w-4" />
										</Button>
									</Table.Cell>
								</Table.Row>
							{/each}
							{#if fda25Data.length === 0}
								<Table.Row>
									<Table.Cell colspan={5} class="py-6 text-center text-muted-foreground"
										>Sin registros</Table.Cell
									>
								</Table.Row>
							{/if}
						</Table.Body>
					</Table.Root>
				</div>
				<div class="flex justify-end gap-2 border-t bg-muted/10 p-4">
					<Button variant="outline" size="sm" class="gap-2" onclick={openNewFda25}>
						<Plus class="h-4 w-4" /> Insertar
					</Button>

					<Dialog.Root bind:open={dialogFda25Open}>
						<Dialog.Content class="sm:max-w-[425px]">
							<Dialog.Header>
								<Dialog.Title>Lot and Production Dates</Dialog.Title>
								<Dialog.Description>
									Agrega o edita la información de lotes y fechas de producción.
								</Dialog.Description>
							</Dialog.Header>

							<div class="grid gap-4 py-4">
								<div class="grid grid-cols-2 gap-4">
									<div class="space-y-2">
										<Label class="text-xs text-muted-foreground">Clave FDA</Label>
										<div class="font-mono text-sm font-medium">{globalFdaCode || '---'}</div>
									</div>
									<div class="space-y-2">
										<Label for="fda25-linea">Línea</Label>
										<Input id="fda25-linea" disabled value={currentFda25.line} class="font-mono" />
									</div>
								</div>

								<div class="space-y-2">
									<Label for="fda25-lot-number">Lot Number</Label>
									<Input id="fda25-lot-number" bind:value={currentFda25.lot_number} />
								</div>

								<div class="grid grid-cols-2 gap-4">
									<div class="space-y-2">
										<Label for="fda25-lot-prod-bd" class="text-xs">Prod. Start Date</Label>
										<Input
											id="fda25-lot-prod-bd"
											type="date"
											bind:value={currentFda25.prod_start_date}
										/>
									</div>
									<div class="space-y-2">
										<Label for="fda25-lot-prod-ed" class="text-xs">Prod. End Date</Label>
										<Input
											id="fda25-lot-prod-ed"
											type="date"
											bind:value={currentFda25.prod_end_date}
										/>
									</div>
								</div>
							</div>

							<Dialog.Footer>
								<Button type="button" variant="outline" onclick={() => (dialogFda25Open = false)}>
									Cancelar
								</Button>
								<Button type="button" onclick={saveFda25}>Guardar Lote</Button>
							</Dialog.Footer>
						</Dialog.Content>
					</Dialog.Root>
				</div>
			</Card.Root>
		</Tabs.Content>

		<Tabs.Content value="fda23" class="mt-2 flex-1">
			<Card.Root class="shadow-sm">
				<Card.Content class="p-6">
					<div class="mb-6 flex items-center justify-between">
						<div class="flex items-center gap-2">
							<ListChecks class="h-5 w-5 text-muted-foreground" />
							<h2 class="text-lg font-semibold">Afirmación de Cumplimiento (FDA23)</h2>
						</div>
						<Button size="sm" onclick={openNewFda23}>
							<Plus class="mr-2 h-4 w-4" /> Agregar Código
						</Button>
					</div>

					<Table.Root>
						<Table.Header>
							<Table.Row>
								<Table.Head class="w-16">Línea</Table.Head>
								<Table.Head>Código (AOC Code)</Table.Head>
								<Table.Head>Calificador (AOC Qual)</Table.Head>
								<Table.Head class="w-24 text-right">Acciones</Table.Head>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{#each fda23Codes as code, idx}
								{#if code.aoc_code || code.aoc_qual}
									<Table.Row>
										<Table.Cell class="font-medium text-muted-foreground">{idx + 1}</Table.Cell>
										<Table.Cell class="font-mono">{code.aoc_code || '-'}</Table.Cell>
										<Table.Cell>{code.aoc_qual || '-'}</Table.Cell>
										<Table.Cell class="text-right">
											<div class="flex justify-end gap-2">
												<Button
													variant="ghost"
													size="icon"
													class="h-8 w-8"
													onclick={() => editFda23(idx)}
												>
													<Pencil class="h-4 w-4" />
												</Button>
												<Button
													variant="ghost"
													size="icon"
													class="h-8 w-8 text-destructive"
													onclick={() => removeFda23(idx)}
												>
													<Trash2 class="h-4 w-4" />
												</Button>
											</div>
										</Table.Cell>
									</Table.Row>
								{/if}
							{/each}
						</Table.Body>
					</Table.Root>

					<!-- Modal para FDA23 -->
					<Dialog.Root bind:open={dialogFda23Open}>
						<Dialog.Content class="max-w-md">
							<Dialog.Header>
								<Dialog.Title>
									{editIndexFda23 !== null ? 'Editar Código' : 'Nuevo Código'} de Afirmación
								</Dialog.Title>
								<Dialog.Description>Gestión de códigos de cumplimiento FDA23</Dialog.Description>
							</Dialog.Header>

							<div class="grid gap-4 py-4">
								<div class="grid grid-cols-4 items-center gap-4">
									<Label class="text-right">Línea</Label>
									<Input type="number" class="col-span-3" bind:value={currentFda23.line} disabled />
								</div>
								<div class="grid grid-cols-4 items-center gap-4">
									<Label class="required text-right">AOC Code</Label>
									<Input
										class="col-span-3 font-mono"
										bind:value={currentFda23.aoc_code}
										placeholder="PNE, REG, etc."
									/>
								</div>
								<div class="grid grid-cols-4 items-center gap-4">
									<Label class="text-right">AOC Qual</Label>
									<Input
										class="col-span-3"
										bind:value={currentFda23.aoc_qual}
										placeholder="Calificador opcional"
									/>
								</div>
							</div>

							<Dialog.Footer>
								<Button variant="outline" onclick={() => (dialogFda23Open = false)}>Cancelar</Button
								>
								<Button onclick={saveFda23}>Guardar</Button>
							</Dialog.Footer>
						</Dialog.Content>
					</Dialog.Root>
				</Card.Content>
			</Card.Root>
		</Tabs.Content>
	</div>

	<div
		class="fixed right-0 bottom-0 left-0 z-[5] ml-[calc(var(--sidebar-width))] border-t bg-background/95 shadow-lg backdrop-blur group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] supports-[backdrop-filter]:bg-background/80"
	>
		<div class="mx-auto max-w-[1400px] px-4 py-4 sm:grid sm:grid-cols-3 sm:items-center">
			<div class="hidden sm:block"></div>

			<div class="flex w-full justify-center pb-4 sm:pb-0">
				<Tabs.List class="grid w-full max-w-md grid-cols-5">
					<Tabs.Trigger value="general">General</Tabs.Trigger>
					<Tabs.Trigger value="fda01">FDA01</Tabs.Trigger>
					<Tabs.Trigger value="fda04">FDA04</Tabs.Trigger>
					<Tabs.Trigger value="fda23">FDA23</Tabs.Trigger>
					<Tabs.Trigger value="fda25">FDA25</Tabs.Trigger>
				</Tabs.List>
			</div>
			<div class="flex justify-center gap-3 sm:justify-end">
				<Button type="button" variant="outline" href="/dashboard/goods/fda-codes">Cancelar</Button>
				<Button type="button" onclick={saveFdaData} disabled={isSaving}>
					<Save size={16} class="mr-2" />
					Guardar
				</Button>
			</div>
		</div>
	</div>
</Tabs.Root>

<CountrySelectorDialog
	bind:open={countryModalOpen}
	onSelect={(country) => {
		formData.country_of_production = country.m3_key || country.mex_key || '';
		countryModalOpen = false;
	}}
/>

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