<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 { Select, SelectContent, SelectItem, SelectTrigger } from '$lib/components/ui/select';
	import { Button } from '$lib/components/ui/button';
	import { Search } from 'lucide-svelte';

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

	const transportOptions = [
		{ value: 'transporte', label: 'Transporte' },
		{ value: 'caja', label: 'Caja' },
		{ value: 'placas', label: 'Placas' },
		{ value: 'camion', label: 'Camión' },
		{ value: 'buque', label: 'Buque' },
		{ value: 'ferrobarcaza', label: 'Ferrobarcaza' },
		{ value: 'contenedor', label: 'Contenedor' },
		{ value: 'avion', label: 'Avión' }
	];

	const defaultFormData = {
		// General
		Conductor: '',
		Transporte: '',
		ImpOrdenComp: false,
		DecimalesPeso: null,
		DecimalesCant: null,
		DecimalesCosto: null,
		DecimalesValor: null,

		// Mexicana
		PorParteClaseMex: 'parte',
		NumParteMex: false,
		TipoFraccMex: false,
		TasaFraccMex: false,
		UMAlternaMex: false,
		PaisOrigenMex: false,
		FraccionImp: false,
		UMEquivalenteMex: false,
		AgregarVAenProdTerminados: false,
		OcultarFechaHora: false,
		ImprimirLote: false,
		ImprimirNumEntrada: false,
		ObservacionFMex: '',
		FirmaFMex: '',

		// Americana (legacy/SCAII)
		PorParteClaseAMe: 'parte',
		NumParteAme: false,
		FraccionAme: false,
		PaisOrigenAme: false,
		UMEquivalenteAme: false,
		LeyendaFacAme: '',
		FirmaFAme: '',

		// Packing List
		PackingOrdenCompra: false,
		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');

	// Conductor picker modal
	let showConductorPicker = $state(false);

	function selectConductor(driver: any) {
		formData.Conductor = driver.name ?? driver.driver_name ?? driver.full_name ?? String(driver);
		showConductorPicker = false;
	}
</script>

<!-- Conductor picker modal -->
{#if showConductorPicker}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
		<div class="bg-background border rounded-xl shadow-xl p-6 w-full max-w-md space-y-4">
			<h3 class="text-base font-semibold">Seleccionar Conductor</h3>
			{#if drivers && drivers.length > 0}
				<ul class="max-h-72 overflow-y-auto divide-y rounded-md border">
					{#each drivers as driver}
						<li>
							<button
								class="w-full text-left px-4 py-2 text-sm hover:bg-muted transition-colors"
								onclick={() => selectConductor(driver)}
							>
								{driver.name ?? driver.driver_name ?? driver.full_name ?? JSON.stringify(driver)}
							</button>
						</li>
					{/each}
				</ul>
			{:else}
				<p class="text-sm text-muted-foreground text-center py-6">No hay conductores registrados.</p>
			{/if}
			<div class="flex justify-end">
				<Button variant="outline" size="sm" onclick={() => showConductorPicker = false}>Cerrar</Button>
			</div>
		</div>
	</div>
{/if}

<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">Generales</Tabs.Trigger>
				<Tabs.Trigger value="mexicana" class="flex-1">Factura Mexicana Bilingüe</Tabs.Trigger>
				{#if activeSystem !== 'qsisgen'}
					<Tabs.Trigger value="americana" class="flex-1">Factura Americana</Tabs.Trigger>
				{/if}
				<Tabs.Trigger value="packing" class="flex-1">Packing List</Tabs.Trigger>
			</Tabs.List>
		</div>

		<!-- GENERAL TAB -->
		<Tabs.Content value="general" class="space-y-6">
			<!-- Conductor y Transporte -->
			<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">Datos de Transporte</h4>
				<div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
					<!-- Conductor -->
					<div class="space-y-1.5">
						<Label class="text-xs">Conductor</Label>
						<div class="flex gap-2">
							<Input
								id="cm_Conductor"
								bind:value={formData.Conductor}
								placeholder="Nombre del conductor..."
								class="h-8 text-sm flex-1"
							/>
							<Button
								variant="outline"
								size="sm"
								class="h-8 px-2"
								onclick={() => showConductorPicker = true}
								title="Buscar conductor del catálogo"
							>
								<Search size={14} />
							</Button>
						</div>
					</div>

					<!-- Tipo de Transporte -->
					<div class="space-y-1.5">
						<Label class="text-xs">Tipo de Transporte</Label>
						<Select
							type="single"
							value={formData.Transporte}
							onValueChange={(v) => (formData.Transporte = v)}
						>
							<SelectTrigger class="h-8 text-sm">
								{transportOptions.find((o) => o.value === formData.Transporte)?.label || 'Seleccionar...'}
							</SelectTrigger>
							<SelectContent>
								{#each transportOptions as opt}
									<SelectItem value={opt.value}>{opt.label}</SelectItem>
								{/each}
							</SelectContent>
						</Select>
					</div>
				</div>

				<!-- Imprimir orden de compra por partida -->
				<div class="flex items-center gap-2 pt-2">
					<Checkbox id="cm_ImpOrdenComp" bind:checked={formData.ImpOrdenComp} />
					<Label for="cm_ImpOrdenComp" class="text-sm">Imprimir la orden de compra por partida</Label>
				</div>
			</div>

			<!-- Número 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 border-b pb-2">Número de Decimales</h4>
				<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 pt-2">
					<div class="space-y-1.5">
						<Label class="text-xs">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">En 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">Costos Unitarios</Label>
						<Input type="number" bind:value={formData.DecimalesCosto} class="h-8 text-sm" />
					</div>
					<div class="space-y-1.5">
						<Label class="text-xs">En Valores</Label>
						<Input type="number" bind:value={formData.DecimalesValor} class="h-8 text-sm" />
					</div>
				</div>
			</div>
		</Tabs.Content>

		<!-- MEXICANA TAB -->
		<Tabs.Content value="mexicana" class="space-y-6">
			{#if activeSystem === 'qsisgen'}
				<!-- SCAF DESIGN (Based on image) -->
				<div class="space-y-6">
					<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
						<!-- Incluir en la descripción (Panel Izquierdo) -->
						<div class="space-y-4 border rounded-md p-4 bg-muted/10 h-full">
							<h4 class="text-xs font-bold text-red-600/80 dark:text-red-400 uppercase border-b pb-2 tracking-tight">
								Incluir en la columna de descripción
							</h4>
							<div class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-3 pt-2">
								<div class="flex items-center gap-2">
									<Checkbox id="cm_TipoFraccMex_scaf" bind:checked={formData.TipoFraccMex} />
									<Label for="cm_TipoFraccMex_scaf" class="text-sm">El Tipo de Fracción.</Label>
								</div>
								<div class="flex items-center gap-2">
									<Checkbox id="cm_PaisOrigenMex_scaf" bind:checked={formData.PaisOrigenMex} />
									<Label for="cm_PaisOrigenMex_scaf" class="text-sm">El país de origen.</Label>
								</div>
								<div class="flex items-center gap-2">
									<Checkbox id="cm_TasaFraccMex_scaf" bind:checked={formData.TasaFraccMex} />
									<Label for="cm_TasaFraccMex_scaf" class="text-sm">La tasa de la Fracción.</Label>
								</div>
								<div class="flex items-center gap-2">
									<Checkbox id="cm_FraccionImp_scaf" bind:checked={formData.FraccionImp} />
									<Label for="cm_FraccionImp_scaf" class="text-sm">La fracción Arancelaria.</Label>
								</div>
								<div class="flex items-center gap-2">
									<Checkbox id="cm_ImprimirLote_scaf" bind:checked={formData.ImprimirLote} />
									<Label for="cm_ImprimirLote_scaf" class="text-sm">Lote</Label>
								</div>
								<div class="flex items-center gap-2">
									<Checkbox id="cm_ImprimirNumEntrada_scaf" bind:checked={formData.ImprimirNumEntrada} />
									<Label for="cm_ImprimirNumEntrada_scaf" class="text-sm">Num. Entrada</Label>
								</div>
							</div>
						</div>

						<!-- Firma (Panel Derecho) -->
						<div class="space-y-4 border rounded-md p-4 bg-muted/10 h-full">
							<Label for="cm_FirmaFMex_scaf" class="text-sm font-semibold block mb-2">Firma en factura:</Label>
							<Textarea 
								id="cm_FirmaFMex_scaf" 
								bind:value={formData.FirmaFMex} 
								class="h-[calc(100%-2rem)] min-h-[120px] resize-none" 
							/>
						</div>
					</div>

					<!-- Observaciones (Panel Inferior) -->
					<div class="space-y-2 border rounded-md p-4 bg-muted/10">
						<Label for="cm_ObservacionFMex_scaf" class="text-sm font-semibold">
							Observación de la Factura Mexicana y Bilingüe:
						</Label>
						<Textarea 
							id="cm_ObservacionFMex_scaf" 
							bind:value={formData.ObservacionFMex} 
							class="h-32 resize-y" 
						/>
					</div>
				</div>
			{:else}
				<!-- SCAII DESIGN (Traditional) -->
				<div class="space-y-6">
					<!-- Imprimir por -->
					<div class="space-y-4 border rounded-md p-4 bg-muted/10">
						<h4 class="text-sm font-semibold text-muted-foreground uppercase">Imprimir por</h4>
						<RadioGroup
							value={formData.PorParteClaseMex}
							onValueChange={(v) => (formData.PorParteClaseMex = v)}
							class="flex gap-4"
						>
							<div class="flex items-center gap-2">
								<RadioGroupItem value="parte" id="cm_mex_imprimir_parte" />
								<Label for="cm_mex_imprimir_parte" class="text-sm">Parte</Label>
							</div>
							<div class="flex items-center gap-2">
								<RadioGroupItem value="clase" id="cm_mex_imprimir_clase" />
								<Label for="cm_mex_imprimir_clase" class="text-sm">Clase</Label>
							</div>
						</RadioGroup>
					</div>

					<!-- Incluir en la columna de descripción -->
					<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 la columna de descripción
						</h4>
						<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 pt-2">
							<div class="flex items-center gap-2">
								<Checkbox id="cm_NumParteMex" bind:checked={formData.NumParteMex} />
								<Label for="cm_NumParteMex" class="text-sm">El número de parte</Label>
							</div>
							<div class="flex items-center gap-2">
								<Checkbox id="cm_TipoFraccMex" bind:checked={formData.TipoFraccMex} />
								<Label for="cm_TipoFraccMex" class="text-sm">El tipo de fracción</Label>
							</div>
							<div class="flex items-center gap-2">
								<Checkbox id="cm_TasaFraccMex" bind:checked={formData.TasaFraccMex} />
								<Label for="cm_TasaFraccMex" class="text-sm">La tasa de fracción</Label>
							</div>
							<div class="flex items-center gap-2">
								<Checkbox id="cm_UMAlternaMex" bind:checked={formData.UMAlternaMex} />
								<Label for="cm_UMAlternaMex" class="text-sm">Cantidad alterna</Label>
							</div>
							<div class="flex items-center gap-2">
								<Checkbox id="cm_PaisOrigenMex" bind:checked={formData.PaisOrigenMex} />
								<Label for="cm_PaisOrigenMex" class="text-sm">El país de origen</Label>
							</div>
							<div class="flex items-center gap-2">
								<Checkbox id="cm_FraccionImp" bind:checked={formData.FraccionImp} />
								<Label for="cm_FraccionImp" class="text-sm">La fracción arancelaria</Label>
							</div>
							<div class="flex items-center gap-2">
								<Checkbox id="cm_UMEquivalenteMex" bind:checked={formData.UMEquivalenteMex} />
								<Label for="cm_UMEquivalenteMex" class="text-sm">La U.M. Equivalente</Label>
							</div>
						</div>

						<!-- Opciones adicionales fuera de la sub-sección -->
						<div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t mt-4">
							<div class="flex items-center gap-2">
								<Checkbox id="cm_AgregarVAenProdTerminados" bind:checked={formData.AgregarVAenProdTerminados} />
								<Label for="cm_AgregarVAenProdTerminados" class="text-sm">Agregar VA en Prod. Terminados</Label>
							</div>
							<div class="flex items-center gap-2">
								<Checkbox id="cm_OcultarFechaHora" bind:checked={formData.OcultarFechaHora} />
								<Label for="cm_OcultarFechaHora" class="text-sm">Ocultar Fecha y Hora</Label>
							</div>
						</div>
					</div>

					<!-- Firma -->
					<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">Firma</h4>
						<div class="space-y-2 pt-2">
							<Textarea id="cm_FirmaFMex" bind:value={formData.FirmaFMex} class="h-24 resize-y" />
						</div>
					</div>
				</div>
			{/if}
		</Tabs.Content>

		<!-- AMERICANA TAB -->
		{#if activeSystem !== 'qsisgen'}
			<Tabs.Content value="americana" class="space-y-6">
				<!-- Imprimir por -->
				<div class="space-y-4 border rounded-md p-4 bg-muted/10">
					<h4 class="text-sm font-semibold text-muted-foreground uppercase">Imprimir por</h4>
					<RadioGroup
						value={formData.PorParteClaseAMe}
						onValueChange={(v) => (formData.PorParteClaseAMe = v)}
						class="flex gap-4"
					>
						<div class="flex items-center gap-2">
							<RadioGroupItem value="parte" id="cm_ame_imprimir_parte" />
							<Label for="cm_ame_imprimir_parte" class="text-sm">Parte</Label>
						</div>
						<div class="flex items-center gap-2">
							<RadioGroupItem value="clase" id="cm_ame_imprimir_clase" />
							<Label for="cm_ame_imprimir_clase" class="text-sm">Clase</Label>
						</div>
					</RadioGroup>
				</div>

				<!-- Incluir en la columna de descripción -->
				<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 la columna de descripción
					</h4>
					<div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
						<div class="flex items-center gap-2">
							<Checkbox id="cm_NumParteAme" bind:checked={formData.NumParteAme} />
							<Label for="cm_NumParteAme" class="text-sm">El número de parte</Label>
						</div>
						<div class="flex items-center gap-2">
							<Checkbox id="cm_FraccionAme" bind:checked={formData.FraccionAme} />
							<Label for="cm_FraccionAme" class="text-sm">La fracción americana</Label>
						</div>
						<div class="flex items-center gap-2">
							<Checkbox id="cm_PaisOrigenAme" bind:checked={formData.PaisOrigenAme} />
							<Label for="cm_PaisOrigenAme" class="text-sm">El país de origen</Label>
						</div>
						<div class="flex items-center gap-2">
							<Checkbox id="cm_UMEquivalenteAme" bind:checked={formData.UMEquivalenteAme} />
							<Label for="cm_UMEquivalenteAme" class="text-sm">La U.M. N. Equivalente</Label>
						</div>
					</div>
				</div>

				<!-- Textos libres -->
				<div class="space-y-4 border rounded-md p-4 bg-muted/10">
					<div class="space-y-2">
						<Label for="cm_LeyendaFacAme" class="text-sm font-semibold text-muted-foreground">
							Leyenda factura
						</Label>
						<Textarea id="cm_LeyendaFacAme" bind:value={formData.LeyendaFacAme} class="h-24 resize-y" />
					</div>
					<div class="space-y-2 pt-4">
						<Label for="cm_FirmaFAme" class="text-sm font-semibold text-muted-foreground">
							Firma en factura americana
						</Label>
						<Textarea id="cm_FirmaFAme" bind:value={formData.FirmaFAme} class="h-24 resize-y" />
					</div>
				</div>
			</Tabs.Content>
		{/if}

		<!-- PACKING LIST TAB -->
		<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 de Packing List
				</h4>
				<div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
					<div class="flex items-center gap-2">
						<Checkbox id="cm_PackingOrdenCompra" bind:checked={formData.PackingOrdenCompra} />
						<Label for="cm_PackingOrdenCompra" class="text-sm">Imprimir orden de compra</Label>
					</div>
					{#if activeSystem !== 'qsisgen'}
						<div class="flex items-center gap-2">
							<Checkbox id="cm_IncluirLineaDelPO" bind:checked={formData.IncluirLineaDelPO} />
							<Label for="cm_IncluirLineaDelPO" class="text-sm">Incluir línea de PO</Label>
						</div>
					{/if}
				</div>
			</div>
		</Tabs.Content>
	</Tabs.Root>
</div>
