<script lang="ts">
	import * as Tabs from '$lib/components/ui/tabs';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Checkbox } from '$lib/components/ui/checkbox';
	import { Textarea } from '$lib/components/ui/textarea';
	import { RadioGroup, RadioGroupItem } from '$lib/components/ui/radio-group';
	import { Button } from '$lib/components/ui/button';

	let {
		formData = $bindable(),
		activeSystem = 'ssisgen'
	}: {
		formData: any;
		activeSystem?: 'ssisgen' | 'qsisgen';
	} = $props();

	const defaultFormData = {
		DecimalesPeso: null,
		DecimalesCant: null,
		DecimalesValor: null,
		DecimalesCosto: null,
		ControlRemesa: false,
		RemesaInicio: null,
		RemesaFinal: null,
		CantLimiteMin: null,
		PesoLimiteMin: null,
		ValorLimiteMin: null,
		ValorLimiteParMin: null,
		CantLimite: null,
		PesoLimite: null,
		ValorLimite: null,
		ValorLimitePar: null,
		RestringeImpoPT: false,
		ActualizarPartePartida: false,
		CalcIGIBaseCapt: false,
		LocAPOrigen: false,
		SolicitarContrasenaAdministrador: false,
		
		// SCAF specific (backend persist)
		pagoimpuesto: 'no',
		formapago: '',

		// Mexicana
		PorParteClaseMex: 'parte',
		NumParteMex: false,
		PaisOrigenMex: false,
		UMEquivalenteMex: false,
		UMAlternaMex: false,
		FraccionImp: false,
		TasaFraccMex: false,
		TipoFraccMex: false, 
		ImpOrdenCom: false, 
		PerPagRenglon: false, 
		ParteComplementariaMex: false,
		ParteCompleMexPartida: false,
		ImprimirLote: false,
		ImprimirNumEntrada: false,
		CodigoBarras: false,
		UMAuxiliarMex: false,
		AgregarVAenProdTerminados: false,
		OcultarFechaHora: false,
		FirmaFMex: '',

		// Americana
		PorParteClaseAMe: 'parte',
		NumParteAme: false,
		FraccionAme: false,
		PaisOrigenAme: false,
		UMEquivalenteAme: false,
		LeyendaFacAme: '',
		FirmaFAme: '',

		// Packing list
		PackingPedClave: false,
		PackingOrdenCompra: false,
		PorOrdenPorOCPack: 'captura',
		IncluirLineaDelPO: false
	};

	if (!formData) {
		formData = { ...defaultFormData };
	} 

	$effect.pre(() => {
		if (formData) {
			for (const key in defaultFormData) {
				if (formData[key] === undefined) {
					formData[key] = defaultFormData[key as keyof typeof defaultFormData];
				}
			}
		}
	});

	let activeSubTab = $state('general');
</script>

<div class="w-full">
	<Tabs.Root bind:value={activeSubTab} class="flex flex-col">
		<div class="w-full overflow-x-auto pb-2 mb-4">
			<Tabs.List class="inline-flex md:flex w-full bg-muted/60 p-1 rounded-md">
				<Tabs.Trigger value="general" class="flex-1">General</Tabs.Trigger>
				<Tabs.Trigger value="mexicana" class="flex-1">Factura Mexicana y Bilingüe</Tabs.Trigger>
				<Tabs.Trigger value="americana" class="flex-1">Factura Americana</Tabs.Trigger>
				<Tabs.Trigger value="packing" class="flex-1">Packing List</Tabs.Trigger>
			</Tabs.List>
		</div>

		<!-- ========================================================================= -->
		<!-- TAB: GENERAL -->
		<!-- ========================================================================= -->
		<Tabs.Content value="general" class="space-y-6">
			<!-- Configuración de Decimales -->
			<div class="space-y-4 border rounded-md p-4 bg-muted/10">
				<h4 class="text-sm font-semibold text-muted-foreground uppercase">Configuración de Decimales</h4>
				<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
					<div class="space-y-1.5">
						<Label class="text-xs">Decimales (Peso Neto y Bruto)</Label>
						<Input type="number" bind:value={formData.DecimalesPeso} class="h-8 text-sm" />
					</div>
					<div class="space-y-1.5">
						<Label class="text-xs">Decimales (Cantidades)</Label>
						<Input type="number" bind:value={formData.DecimalesCant} class="h-8 text-sm" />
					</div>
					<div class="space-y-1.5">
						<Label class="text-xs">Decimales (Valores)</Label>
						<Input type="number" bind:value={formData.DecimalesValor} class="h-8 text-sm" />
					</div>
					<div class="space-y-1.5">
						<Label class="text-xs">Decimales (Costos Unitarios)</Label>
						<Input type="number" bind:value={formData.DecimalesCosto} class="h-8 text-sm" />
					</div>
				</div>
			</div>

			<!-- SCAII: Control Remesa -->
			{#if activeSystem === 'ssisgen'}
				<div class="space-y-4 border rounded-md p-4 bg-muted/10">
					<div class="flex items-center gap-2 mb-2 border-b pb-2">
						<Checkbox id="ControlRemesa" bind:checked={formData.ControlRemesa} />
						<Label for="ControlRemesa" class="font-semibold text-muted-foreground uppercase">Control Remesa por Rangos</Label>
					</div>
					<div class="grid grid-cols-1 md:grid-cols-2 gap-4" class:opacity-50={!formData.ControlRemesa}>
						<div class="space-y-1.5">
							<Label class="text-xs">De la Remesa</Label>
							<Input type="number" bind:value={formData.RemesaInicio} disabled={!formData.ControlRemesa} class="h-8 text-sm" />
						</div>
						<div class="space-y-1.5">
							<Label class="text-xs">A la Remesa</Label>
							<Input type="number" bind:value={formData.RemesaFinal} disabled={!formData.ControlRemesa} class="h-8 text-sm" />
						</div>
					</div>
				</div>
			{/if}

			<!-- SCAF: Sub sección Partidas & Formas de Pago -->
			{#if activeSystem === 'qsisgen'}
				<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
					<div class="space-y-4 border rounded-md p-4 bg-muted/10">
						<h4 class="text-sm font-semibold text-muted-foreground uppercase border-b pb-2">Sub sección Partidas</h4>
						<div class="space-y-3">
							<Label class="text-sm font-medium">¿Se pagó el impuesto?</Label>
							<RadioGroup value={formData.pagoimpuesto} onValueChange={(v) => formData.pagoimpuesto = v} class="flex gap-4">
								<div class="flex items-center gap-2">
									<RadioGroupItem value="si" id="pago_si" />
									<Label for="pago_si" class="text-sm cursor-pointer">Si</Label>
								</div>
								<div class="flex items-center gap-2">
									<RadioGroupItem value="no" id="pago_no" />
									<Label for="pago_no" class="text-sm cursor-pointer">No</Label>
								</div>
							</RadioGroup>
						</div>
					</div>
					<div class="space-y-4 border rounded-md p-4 bg-muted/10">
						<h4 class="text-sm font-semibold text-muted-foreground uppercase border-b pb-2">Formas de Pago</h4>
						<div class="space-y-2">
							<Label class="text-sm font-medium">Seleccionar Forma de Pago</Label>
							<div class="flex gap-2">
								<Input bind:value={formData.formapago} placeholder="Ej. 0, 21..." class="h-9" />
								<Button variant="outline" size="sm" class="h-9 px-3 shrink-0">Catálogo</Button>
							</div>
						</div>
					</div>
				</div>
			{/if}

			<!-- Limites Min/Max (Shared) -->
			<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
				<div class="space-y-4 border rounded-md p-4 bg-muted/10">
					<h4 class="text-sm font-semibold text-muted-foreground uppercase border-b pb-2">Mínimos límites para actualizar</h4>
					<div class="grid grid-cols-2 gap-4 pt-2">
						<div class="space-y-1"><Label class="text-[10px]">Cantidad</Label><Input type="number" bind:value={formData.CantLimiteMin} class="h-7 text-xs" /></div>
						<div class="space-y-1"><Label class="text-[10px]">Peso</Label><Input type="number" bind:value={formData.PesoLimiteMin} class="h-7 text-xs" /></div>
						<div class="space-y-1"><Label class="text-[10px]">Valor</Label><Input type="number" bind:value={formData.ValorLimiteMin} class="h-7 text-xs" /></div>
						<div class="space-y-1"><Label class="text-[10px]">Valor Part.</Label><Input type="number" bind:value={formData.ValorLimiteParMin} class="h-7 text-xs" /></div>
					</div>
				</div>
				<div class="space-y-4 border rounded-md p-4 bg-muted/10">
					<h4 class="text-sm font-semibold text-muted-foreground uppercase border-b pb-2">Máximos límites para actualizar</h4>
					<div class="grid grid-cols-2 gap-4 pt-2">
						<div class="space-y-1"><Label class="text-[10px]">Cantidad</Label><Input type="number" bind:value={formData.CantLimite} class="h-7 text-xs" /></div>
						<div class="space-y-1"><Label class="text-[10px]">Peso</Label><Input type="number" bind:value={formData.PesoLimite} class="h-7 text-xs" /></div>
						<div class="space-y-1"><Label class="text-[10px]">Valor</Label><Input type="number" bind:value={formData.ValorLimite} class="h-7 text-xs" /></div>
						<div class="space-y-1"><Label class="text-[10px]">Valor Part.</Label><Input type="number" bind:value={formData.ValorLimitePar} class="h-7 text-xs" /></div>
					</div>
				</div>
			</div>

			<!-- Otras Opciones -->
			<div class="space-y-4 border rounded-md p-4 bg-muted/10">
				<h4 class="text-sm font-semibold text-muted-foreground uppercase border-b pb-2">Otras Opciones</h4>
				{#if activeSystem === 'qsisgen'}
					<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
						<div class="flex items-center gap-2">
							<Checkbox id="scaf_ActualizarParte" bind:checked={formData.ActualizarPartePartida} />
							<Label for="scaf_ActualizarParte" class="text-sm">Actualizar datos del número de parte en base de a la captura de las partidas</Label>
						</div>
						<div class="flex items-center gap-2">
							<Checkbox id="scaf_SolicitarAuth" bind:checked={formData.SolicitarContrasenaAdministrador} />
							<Label for="scaf_SolicitarAuth" class="text-sm font-bold">
								Solicitar autorizacion para pasar por alto la validacion de tipo de cambio de fecha de pago de pedimento
							</Label>
						</div>
					</div>
				{:else}
					<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
						<div class="flex items-center gap-2"><Checkbox id="RestringeImpoPT" bind:checked={formData.RestringeImpoPT} /><Label for="RestringeImpoPT" class="text-sm">Restringe la importación de Productos Terminados</Label></div>
						<div class="flex items-center gap-2"><Checkbox id="ActualizarPartePartida" bind:checked={formData.ActualizarPartePartida} /><Label for="ActualizarPartePartida" class="text-sm">Actualiza datos del número de parte en base a captura de partidas</Label></div>
						<div class="flex items-center gap-2"><Checkbox id="CalcIGIBaseCapt" bind:checked={formData.CalcIGIBaseCapt} /><Label for="CalcIGIBaseCapt" class="text-sm">Cálculo del Valor IGI en Base a lo capturado</Label></div>
						<div class="flex items-center gap-2"><Checkbox id="LocAPOrigen" bind:checked={formData.LocAPOrigen} /><Label for="LocAPOrigen" class="text-sm">Advertencia País de Origen</Label></div>
						<div class="flex items-center gap-2 col-span-2"><Checkbox id="SolicitarContrasenaAdministrador" bind:checked={formData.SolicitarContrasenaAdministrador} /><Label for="SolicitarContrasenaAdministrador" class="text-sm">Solicitar Autorización para Pasar por Alto la Validacion de Temporalidad en Base a Fecha de Pago de Pedimento</Label></div>
					</div>
				{/if}
			</div>
		</Tabs.Content>

		<!-- ========================================================================= -->
		<!-- TAB: MEXICANA -->
		<!-- ========================================================================= -->
		<Tabs.Content value="mexicana" class="space-y-6">
			{#if activeSystem === 'qsisgen'}
				<!-- SCAF LAYOUT (Modern Style) -->
				<div class="space-y-6">
					<div class="space-y-4 border rounded-md p-4 bg-muted/10">
						<h4 class="text-sm font-semibold text-muted-foreground uppercase border-b pb-2">Factura Mexicana y Bilingüe</h4>
						
						<div class="flex items-center gap-2 mb-4">
							<Checkbox id="scaf_CodigoBarras" bind:checked={formData.CodigoBarras} />
							<Label for="scaf_CodigoBarras" class="text-sm">Imprimir Código de Barras en la parte inferior de la factura.</Label>
						</div>

						<div class="space-y-4 border rounded-md p-4 bg-muted/5">
							<h4 class="text-sm font-semibold text-muted-foreground uppercase border-b pb-2">Incluir en la columna de descripción</h4>
							<div class="grid grid-cols-1 md:grid-cols-3 gap-6 pt-2">
								<!-- Column 1 -->
								<div class="space-y-3">
									<div class="flex items-center gap-2">
										<Checkbox id="m1_pais" bind:checked={formData.PaisOrigenMex} />
										<Label for="m1_pais" class="text-sm">El País de Origen.</Label>
									</div>
									<div class="flex items-center gap-2">
										<Checkbox id="m1_perm" bind:checked={formData.PerPagRenglon} />
										<Label for="m1_perm" class="text-sm">Permiso y la Página - Renglón.</Label>
									</div>
									<div class="flex flex-col gap-0.5">
										<div class="flex items-center gap-2">
											<Checkbox id="m1_ord" bind:checked={formData.ImpOrdenCom} />
											<Label for="m1_ord" class="text-sm">Orden de Compra.</Label>
										</div>
										<span class="text-[10px] text-muted-foreground ml-6 font-medium">(Facturas y Packing List)</span>
									</div>
								</div>
								<!-- Column 2 -->
								<div class="space-y-3">
									<div class="flex items-center gap-2">
										<Checkbox id="m2_frac" bind:checked={formData.FraccionImp} />
										<Label for="m2_frac" class="text-sm">Fracción Arancelaria.</Label>
									</div>
									<div class="flex items-center gap-2">
										<Checkbox id="m2_tasa" bind:checked={formData.TasaFraccMex} />
										<Label for="m2_tasa" class="text-sm">Tasa de la Fracción Arancelaria.</Label>
									</div>
									<div class="flex items-center gap-2">
										<Checkbox id="m2_pref" bind:checked={formData.TipoFraccMex} />
										<Label for="m2_pref" class="text-sm">La Preferencia de la Fracción Arancelaria.</Label>
									</div>
									<div class="flex items-center gap-2">
										<Checkbox id="m2_num" bind:checked={formData.NumParteMex} />
										<Label for="m2_num" class="text-sm">Número de Parte.</Label>
									</div>
								</div>
								<!-- Column 3 -->
								<div class="space-y-3">
									<div class="flex items-center gap-2">
										<Checkbox id="m3_lote" bind:checked={formData.ImprimirLote} />
										<Label for="m3_lote" class="text-sm">Lote</Label>
									</div>
									<div class="flex items-center gap-2">
										<Checkbox id="m3_ent" bind:checked={formData.ImprimirNumEntrada} />
										<Label for="m3_ent" class="text-sm">Num. Entrada</Label>
									</div>
								</div>
							</div>
						</div>

						<div class="space-y-2 pt-4 flex flex-col items-center">
							<Label for="scaf_Firma" class="text-xs font-semibold text-muted-foreground">Firma en Factura Mexicana:</Label>
							<Textarea id="scaf_Firma" bind:value={formData.FirmaFMex} class="h-24 w-full max-w-xl resize-y" />
						</div>
					</div>
				</div>
			{:else}
				<!-- SCAII LAYOUT -->
				<div class="space-y-6">
					<div class="space-y-4 border rounded-md p-4 bg-muted/10">
						<h4 class="text-sm font-semibold text-muted-foreground uppercase border-b pb-2">Imprimir por</h4>
						<RadioGroup value={formData.PorParteClaseMex} onValueChange={(v) => formData.PorParteClaseMex = v} class="flex gap-6">
							<div class="flex items-center gap-2"><RadioGroupItem value="parte" id="s_p" /><Label for="s_p" class="text-sm">Parte</Label></div>
							<div class="flex items-center gap-2"><RadioGroupItem value="clase" id="s_c" /><Label for="s_c" class="text-sm">Clase</Label></div>
						</RadioGroup>
					</div>
					<div class="space-y-4 border rounded-md p-4 bg-muted/10">
						<h4 class="text-sm font-semibold text-muted-foreground uppercase border-b pb-2">Incluir en descripción</h4>
						<div class="grid grid-cols-2 md:grid-cols-3 gap-4">
							<div class="flex items-center gap-2"><Checkbox id="sn_p" bind:checked={formData.NumParteMex} /><Label for="sn_p" class="text-xs">Número de parte</Label></div>
							<div class="flex items-center gap-2"><Checkbox id="sn_o" bind:checked={formData.PaisOrigenMex} /><Label for="sn_o" class="text-xs">País de origen</Label></div>
							<div class="flex items-center gap-2"><Checkbox id="sn_e" bind:checked={formData.UMEquivalenteMex} /><Label for="sn_e" class="text-xs">U.M. Equivalente</Label></div>
							<div class="flex items-center gap-2"><Checkbox id="sn_a" bind:checked={formData.UMAlternaMex} /><Label for="sn_a" class="text-xs">Cantidad Alterna</Label></div>
							<div class="flex items-center gap-2"><Checkbox id="sn_f" bind:checked={formData.FraccionImp} /><Label for="sn_f" class="text-xs">Fracción Arancelaria</Label></div>
							<div class="flex items-center gap-2"><Checkbox id="sn_t" bind:checked={formData.TasaFraccMex} /><Label for="sn_t" class="text-xs">Tasa Fracción</Label></div>
						</div>
					</div>
					<div class="space-y-2 border rounded-md p-4 bg-muted/10">
						<Label class="text-sm font-semibold">Firma Mexicana</Label>
						<Textarea bind:value={formData.FirmaFMex} class="h-20" />
					</div>
				</div>
			{/if}
		</Tabs.Content>

		<!-- ========================================================================= -->
		<!-- TAB: AMERICANA -->
		<!-- ========================================================================= -->
		<Tabs.Content value="americana" class="space-y-6">
			<div class="space-y-4 border rounded-md p-4 bg-muted/10">
				<h4 class="text-sm font-semibold text-muted-foreground uppercase border-b pb-2">Incluir en descripción</h4>
				<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
					<div class="flex items-center gap-2"><Checkbox id="a_p" bind:checked={formData.NumParteAme} /><Label for="a_p" class="text-sm">Número de parte</Label></div>
					<div class="flex items-center gap-2"><Checkbox id="a_f" bind:checked={formData.FraccionAme} /><Label for="a_f" class="text-sm">Fracción Americana</Label></div>
					<div class="flex items-center gap-2"><Checkbox id="a_o" bind:checked={formData.PaisOrigenAme} /><Label for="a_o" class="text-sm">País de origen</Label></div>
					{#if activeSystem === 'ssisgen'}
						<div class="flex items-center gap-2"><Checkbox id="a_e" bind:checked={formData.UMEquivalenteAme} /><Label for="a_e" class="text-sm">U.M. Equivalente</Label></div>
					{/if}
				</div>
			</div>
			<div class="space-y-4 border rounded-md p-4 bg-muted/10">
				{#if activeSystem === 'ssisgen'}
					<div class="space-y-2">
						<Label class="text-xs font-semibold text-muted-foreground uppercase">Leyenda factura</Label>
						<Textarea bind:value={formData.LeyendaFacAme} class="h-20" />
					</div>
				{/if}
				<div class="space-y-2">
					<Label class="text-xs font-semibold text-muted-foreground uppercase">Firma en factura americana</Label>
					<Textarea bind:value={formData.FirmaFAme} class="h-24 resize-y" />
				</div>
			</div>
		</Tabs.Content>

		<!-- ========================================================================= -->
		<!-- TAB: PACKING -->
		<!-- ========================================================================= -->
		<Tabs.Content value="packing" class="space-y-6">
			<div class="space-y-4 border rounded-md p-4 bg-muted/10">
				<h4 class="text-sm font-semibold text-muted-foreground uppercase border-b pb-2">Opciones</h4>
				<div class="space-y-3">
					<div class="flex items-center gap-2">
						<Checkbox id="p_oc" bind:checked={formData.PackingOrdenCompra} />
						<Label for="p_oc" class="text-sm">
							{activeSystem === 'qsisgen' ? 'imprimir orden de compra' : 'Imprimir orden de compra'}
						</Label>
					</div>
					{#if activeSystem === 'ssisgen'}
						<div class="flex items-center gap-2"><Checkbox id="p_pc" bind:checked={formData.PackingPedClave} /><Label for="p_pc" class="text-sm">Muestra pedimento y clave</Label></div>
						<div class="flex items-center gap-2"><Checkbox id="p_pl" bind:checked={formData.IncluirLineaDelPO} /><Label for="p_pl" class="text-sm">Incluir línea de PO</Label></div>
					{/if}
				</div>
			</div>
		</Tabs.Content>
	</Tabs.Root>
</div>
