<script lang="ts">
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import * as Select from '$lib/components/ui/select';
	import * as RadioGroup from '$lib/components/ui/radio-group';
	import { Button } from '$lib/components/ui/button';
	import { Search, Upload } from 'lucide-svelte';
	import ManifestSelectorModal from './ManifestSelectorModal.svelte';
	import type { Invoice } from '$lib/api/dashboard/a76/invoices';
	import type { InvoiceType } from '$lib/api/dashboard/reference_data/invoice_types';
	import type { CustomsBroker } from '$lib/api/dashboard/a76/customs-brokers';
	import type { ClientProvider } from '$lib/api/dashboard/a76/clients-providers';

	interface CodePedimentoRegimen {
		regimen_code: string;
		type_code: string;
		[key: string]: any;
	}

	let {
		invoice,
		formData = $bindable(),
		customsBrokers = [],
		clients = [],
		providers = [],
		currencyTypes = [],
		transporters = [],
		vehicles = [],
		drivers = [],
		trailers = [],
		customsSections = [],
		codePedimentoRegimens = [],
		operationType = undefined,
		defaultOperationType = undefined,
		exchangeRate = undefined,
		invoiceType = undefined
	}: {
		invoice: Invoice | null;
		formData?: any;
		invoiceTypes?: InvoiceType[];
		customsBrokers?: CustomsBroker[];
		clients?: ClientProvider[];
		providers?: any[];
		currencyTypes?: any[];
		transportTypes?: any[];
		transporters?: any[];
		vehicles?: any[];
		drivers?: any[];
		trailers?: any[];
		customsSections?: any[];
		codePedimentoRegimens?: CodePedimentoRegimen[];
		defaultOperationType?: string | number | null;
		defaultInvoiceType?: string | null;
		operationType?: number | null;
		exchangeRate?: number | null;
		invoiceType?: string;
	} = $props();

	let showManifestModal = $state(false);

	function handleManifestSelect(manifest: any) {
		formData.manifest_number = manifest.manifest_number;
	}

	// Sync exchangeRate prop to formData
	$effect(() => {
		if (exchangeRate !== undefined && formData) {
			formData.exchange_rate = exchangeRate;
		}
	});

	if (!formData) {
		if (invoice) {
			// Editando una factura existente
			formData = {
				// LEFT fields
				provider_header: invoice.compliance_mx?.provider_header || 'proveedor',
				provider_id: invoice.compliance_mx?.provider_id || null,
				sold_to_header: invoice.compliance_mx?.sold_to_header || 'consignado_a',
				sold_to_id: invoice.compliance_mx?.sold_to_id || null,
				shipped_to_header: invoice.compliance_mx?.shipped_to_header || 'enviado_a',
				shipped_to_id: invoice.compliance_mx?.shipped_to_id || null,
				shipped_by_header: invoice.compliance_mx?.shipped_by_header || 'enviado_por',
				shipped_by_id: invoice.compliance_mx?.shipped_by_id || null,
				customs_broker_id: invoice.compliance_mx?.customs_broker_id || null,
				customs_broker_us_id: invoice.compliance_mx?.customs_broker_us_id || null,

				// RIGHT fields
				currency_type: invoice.financials?.currency_type || '',
				currency: invoice.financials?.currency || 'foreign', // foreign, local, manual
				exchange_rate: invoice.financials?.exchange_rate || null, // Added exchange_rate
				weight_type: 'kgs',
				iva_factor: invoice.financials?.iva_factor || null,
				carrier_id: invoice.logistics?.carrier_id || null,
				transport_id: invoice.logistics?.transport_id || '',
				driver_name: invoice.logistics?.driver_name || '',
				transport_type: invoice.logistics?.transport_type || '',
				transport_num: invoice.logistics?.vehicle_num || '',
				aduana: invoice.compliance_mx?.aduana || '',
				document_type: invoice.document_type || '',
				manifest_number: invoice.compliance_mx?.manifest_number || '',
				code_signature: invoice.compliance_mx?.signature_key || '',
				electronic_signature: invoice.compliance_mx?.electronic_signature || ''
			};
		} else {
			// Creando una nueva factura
			formData = {
				// LEFT fields
				provider_header: 'proveedor',
				provider_id: null,
				sold_to_header: 'consignado_a',
				sold_to_id: null,
				shipped_to_header: 'enviado_a',
				shipped_to_id: null,
				shipped_by_header: 'enviado_por',
				shipped_by_id: null,
				customs_broker_id: null,
				customs_broker_us_id: null,

				// RIGHT fields
				currency_type: '',
				currency: 'foreign', // foreign, local, manual
				exchange_rate: null, // Added exchange_rate
				weight_type: 'kgs',
				iva_factor: null,
				carrier_id: null,
				transport_id: '',
				driver_name: '',
				transport_type: '',
				transport_num: '',
				aduana: '',
				document_type: '',
				manifest_number: '',
				code_signature: '',
				electronic_signature: ''
			};
		}
	} else {
		// Si formData ya existe, asegurar que tiene valores por defecto
		if (formData.currency === undefined) {
			formData.currency = 'foreign';
		}
		if (!formData.provider_header) {
			formData.provider_header = 'proveedor';
		}
		if (!formData.sold_to_header) {
			formData.sold_to_header = 'consignado_a';
		}
		if (!formData.shipped_to_header) {
			formData.shipped_to_header = 'enviado_a';
		}
		if (!formData.shipped_by_header) {
			formData.shipped_by_header = 'enviado_por';
		}
		if (formData.manifest_number === undefined) {
			formData.manifest_number = '';
		}
		if (formData.code_signature === undefined) {
			formData.code_signature = '';
		}
		if (formData.electronic_signature === undefined) {
			formData.electronic_signature = '';
		}
	}

	// Opciones de tipo de peso
	const weightTypeOptions = [
		{ value: 'kgs', label: 'Kilogramos (kg)' },
		{ value: 'lbs', label: 'Libras (lb)' }
	];

	// Opciones de tipo de transporte
	const transportTypeOptions = [
		{ value: 'none', label: 'Ninguno' },
		{ value: 'transport', label: 'Transporte' },
		{ value: 'box', label: 'Caja' },
		{ value: 'licence_plates', label: 'Placas' },
		{ value: 'truck', label: 'Camión' },
		{ value: 'vessel', label: 'Buque' },
		{ value: 'rail_barge', label: 'Ferrobarcaza' },
		{ value: 'container', label: 'Contenedor' },
		{ value: 'airplane', label: 'Avión' },
		{ value: 'gondola', label: 'Góndola' },
		{ value: 'flatbed', label: 'Plataforma' }
	];

	// Opciones de encabezados
	const providerHeaderOptions = [
		{ value: 'proveedor', label: 'Proveedor' },
		{ value: 'exportador', label: 'Exportador' }
	];

	const soldToHeaderOptions = $derived([
		{ value: 'consignado_a', label: 'Consignado a' },
		{ value: 'vendido_a', label: 'Vendido a' },
		{
			value: operationType === 1 ? 'exportado_a' : 'importador',
			label: operationType === 1 ? 'Exportado a' : 'Importador'
		}
	]);

	const shippedToHeaderOptions = $derived(
		operationType === 1 || invoiceType === 'CR'
			? [
					{ value: 'enviado_a', label: 'Enviado a' },
					{ value: 'transferido_a', label: 'Transferido a' },
					{ value: 'donado_a', label: 'Donado a' },
					{ value: 'importador', label: 'Importador' }
				]
			: [
					{ value: 'enviado_a', label: 'Enviado a' },
					{ value: 'transferido_a', label: 'Transferido a' }
				]
	);

	const shippedByHeaderOptions = $derived(
		operationType === 1 || invoiceType === 'CR'
			? [
					{ value: 'enviado_por', label: 'Enviado Por' },
					{ value: 'destinatario', label: 'Destinatario' },
					{ value: 'vendido_por', label: 'Vendido Por' },
					{ value: 'consignado_a', label: 'Consignado a' },
					{ value: 'vendido_a', label: 'Vendido a' },
					{ value: 'exportado_a', label: 'Exportado a' },
					{ value: 'enviado_a', label: 'Enviado a' },
					{ value: 'transferido_a', label: 'Transferido a' },
					{ value: 'donado_a', label: 'Donado a' },
					{ value: 'notificar_a', label: 'Notificar a' }
				]
			: [
					{ value: 'enviado_a', label: 'Enviado a' },
					{ value: 'transferido_a', label: 'Transferido a' }
				]
	);

	// Combinar clientes y proveedores para shipped_to, evitando duplicados de tipo "both"
	const allClientsProviders = $derived.by(() => {
		const uniqueMap = new Map();

		// Agregar todos los clientes
		clients.forEach((c) => {
			uniqueMap.set(c.id, { ...c, type: c.client_or_provider });
		});

		// Agregar proveedores solo si no existen (evita duplicados de "both")
		providers.forEach((p) => {
			if (!uniqueMap.has(p.id)) {
				uniqueMap.set(p.id, { ...p, type: p.client_or_provider });
			}
		});

		return Array.from(uniqueMap.values());
	});

	// Determinar tipo de código basado en operationType prop, defaultOperationType o invoice.operation_type
	const typeCode = $derived(
		operationType === 1
			? 'E'
			: operationType === 2
				? 'I'
				: defaultOperationType === 1
					? 'E'
					: defaultOperationType === 2
						? 'I'
						: defaultOperationType === 'exp'
							? 'E'
							: defaultOperationType === 'imp'
								? 'I'
								: invoice?.operation_type === 'exp'
									? 'E'
									: invoice?.operation_type === 'imp'
										? 'I'
										: null
	);

	// Filtrar regímenes por tipo de operación (1='E' exp, 2='I' imp) y obtener valores únicos
	const filteredRegimens = $derived<CodePedimentoRegimen[]>(
		!codePedimentoRegimens || codePedimentoRegimens.length === 0 || !typeCode
			? []
			: Array.from(
					codePedimentoRegimens
						.filter((r) => r.type_code === typeCode)
						.reduce((map, r) => {
							if (r.regimen_code && !map.has(r.regimen_code)) {
								map.set(r.regimen_code, r);
							}
							return map;
						}, new Map<string, CodePedimentoRegimen>())
						.values()
				)
	);

	// Efecto: Limpiar régimen si no existe en los regímenes filtrados al cambiar operation_type
	$effect(() => {
		if (formData.document_type && filteredRegimens.length > 0) {
			const regimenExists = filteredRegimens.some((r) => r.regimen_code === formData.document_type);
			if (!regimenExists) {
				formData.document_type = '';
			}
		}
	});
</script>

<!-- Layout de 2 columnas compacto -->
<div class="grid grid-cols-2 gap-4">
	<!-- Columna Izquierda: Clientes - Proveedores - Agente Aduanal -->
	<div class="space-y-3 rounded-md border p-3">
		{#if invoiceType !== 'MEX'}
			<h4 class="text-xs font-semibold text-muted-foreground uppercase">Datos del pedimento</h4>
			<div class="grid grid-cols-4 gap-3 text-xs">
				<div>
					<span class="text-muted-foreground">Fecha del:</span>
					<p class="font-medium">{formData.fecha_pedimento_del || '-'}</p>
				</div>
				<div>
					<span class="text-muted-foreground">Fecha al:</span>
					<p class="font-medium">{formData.fecha_pedimento_al || '-'}</p>
				</div>
				<div>
					<span class="text-muted-foreground">Clave:</span>
					<p class="font-medium">{formData.clave_pedimento || '-'}</p>
				</div>
				<div>
					<span class="text-muted-foreground">Régimen:</span>
					<p class="font-medium">{formData.regimen_pedimento || '-'}</p>
				</div>
			</div>
		{/if}

		<h4 class="text-xs font-semibold text-muted-foreground uppercase">
			Clientes - Proveedores - Agente Aduanal
		</h4>
		<div class="grid grid-cols-4 gap-3 space-y-1.5">
			<Select.Root
				type="single"
				value={formData.provider_header || providerHeaderOptions[0]?.value || ''}
				onValueChange={(v) => {
					formData.provider_header = v ?? '';
				}}
			>
				<Select.Trigger id="provider_header" class="h-7 max-w-[250px] min-w-[125px] text-xs">
					<span class="truncate">
						{providerHeaderOptions.find(
							(o) => o.value === (formData.provider_header || providerHeaderOptions[0]?.value)
						)?.label || 'Selecciona encabezado...'}
					</span>
				</Select.Trigger>
				<Select.Content>
					{#each providerHeaderOptions as option}
						<Select.Item value={option.value}>
							{option.label}
						</Select.Item>
					{/each}
				</Select.Content>
			</Select.Root>
			<Select.Root
				type="single"
				value={formData.provider_id ? String(formData.provider_id) : ''}
				onValueChange={(v) => {
					formData.provider_id = v ? parseInt(v) : null;
				}}
			>
				<Select.Trigger id="provider_id" class="h-7 max-w-[250px] min-w-[120px] text-xs">
					<span class="truncate">
						{#if formData.provider_id}
							{providers.find((p) => p.id === formData.provider_id)?.name || 'Selecciona...'}
						{:else}
							Selecciona...
						{/if}
					</span>
				</Select.Trigger>
				<Select.Content class="max-h-[300px]">
					{#each providers as provider}
						<Select.Item value={String(provider.id)}>
							{provider.name}
						</Select.Item>
					{/each}
				</Select.Content>
			</Select.Root>
			<span class="text-red-500">*</span>
		</div>

		<div class="grid grid-cols-4 gap-3 space-y-1.5">
			<Select.Root
				type="single"
				value={formData.sold_to_header || soldToHeaderOptions[0]?.value || ''}
				onValueChange={(v) => {
					formData.sold_to_header = v ?? '';
				}}
			>
				<Select.Trigger id="sold_to_header" class="h-7 max-w-[250px] min-w-[125px] text-xs">
					<span class="truncate">
						{soldToHeaderOptions.find(
							(o) => o.value === (formData.sold_to_header || soldToHeaderOptions[0]?.value)
						)?.label || 'Selecciona encabezado...'}
					</span>
				</Select.Trigger>
				<Select.Content>
					{#each soldToHeaderOptions as option}
						<Select.Item value={option.value}>
							{option.label}
						</Select.Item>
					{/each}
				</Select.Content>
			</Select.Root>
			<Select.Root
				type="single"
				value={formData.sold_to_id ? String(formData.sold_to_id) : ''}
				onValueChange={(v) => {
					formData.sold_to_id = v ? parseInt(v) : null;
				}}
			>
				<Select.Trigger id="sold_to_id" class="h-7 max-w-[250px] min-w-[120px] text-xs">
					<span class="truncate">
						{#if formData.sold_to_id}
							{clients.find((c) => c.id === formData.sold_to_id)?.name || 'Selecciona...'}
						{:else}
							Selecciona...
						{/if}
					</span>
				</Select.Trigger>
				<Select.Content class="max-h-[300px]">
					{#each clients as client}
						<Select.Item value={String(client.id)}>
							{client.name}
						</Select.Item>
					{/each}
				</Select.Content>
			</Select.Root>
			<span class="text-red-500">*</span>
		</div>

		<div class="grid grid-cols-4 gap-3 space-y-1.5">
			<Select.Root
				type="single"
				value={formData.shipped_to_header || shippedToHeaderOptions[0]?.value || ''}
				onValueChange={(v) => {
					formData.shipped_to_header = v ?? '';
				}}
			>
				<Select.Trigger id="shipped_to_header" class="h-7 text-xs min-w-[125px] max-w-[250px]">
					<span class="truncate">
						{shippedToHeaderOptions.find(
							(o) => o.value === (formData.shipped_to_header || shippedToHeaderOptions[0]?.value)
						)?.label || 'Selecciona encabezado...'}
					</span>
				</Select.Trigger>
				<Select.Content class="max-h-[300px]">
					{#each shippedToHeaderOptions as option}
						<Select.Item value={option.value}>
							{option.label}
						</Select.Item>
					{/each}
				</Select.Content>
			</Select.Root>
			<Select.Root
				type="single"
				value={formData.shipped_to_id ? String(formData.shipped_to_id) : ''}
				onValueChange={(v) => {
					formData.shipped_to_id = v ? parseInt(v) : null;
				}}
			>
				<Select.Trigger id="shipped_to_id" class="h-7 text-xs min-w-[120px] max-w-[250px]">
					<span class="truncate">
						{#if formData.shipped_to_id}
							{allClientsProviders.find((cp) => cp.id === formData.shipped_to_id)?.name ||
								'Selecciona...'}
						{:else}
							Selecciona...
						{/if}
					</span>
				</Select.Trigger>
				<Select.Content class="max-h-[300px]">
					{#each allClientsProviders as cp}
						<Select.Item value={String(cp.id)}>
							{cp.name}
						</Select.Item>
					{/each}
				</Select.Content>
			</Select.Root>
			<span class="text-red-500">*</span>
		</div>

		<div class="space-y-1.5">
			<Label for="customs_broker_id" class="text-xs"
				>Agente Aduanal Mex: <span class="text-red-500">*</span></Label
			>
			<Select.Root
				type="single"
				value={formData.customs_broker_id ? String(formData.customs_broker_id) : ''}
				onValueChange={(v) => {
					formData.customs_broker_id = v ? parseInt(v) : null;
				}}
			>
				<Select.Trigger id="customs_broker_id" class="h-7 text-xs min-w-[150px] max-w-[300px]">
					<span class="truncate">
						{formData.customs_broker_id
							? customsBrokers.find((cb) => cb.id === formData.customs_broker_id)?.name ||
								'Selecciona...'
							: 'Selecciona...'}
					</span>
				</Select.Trigger>
				<Select.Content class="max-h-[300px]">
					{#each customsBrokers as broker}
						<Select.Item value={broker.id.toString()}>
							{broker.name}
						</Select.Item>
					{/each}
				</Select.Content>
			</Select.Root>
		</div>

		<div class="space-y-1.5">
			<Label for="customs_broker_us_id" class="text-xs">Agente Aduanal Ame:</Label>
			<Select.Root
				type="single"
				value={formData.customs_broker_us_id ? String(formData.customs_broker_us_id) : ''}
				onValueChange={(v) => {
					formData.customs_broker_us_id = v ? parseInt(v) : null;
				}}
			>
				<Select.Trigger id="customs_broker_us_id" class=" h-7 min-w-[150px] text-xs">
					<span class="truncate">
						{formData.customs_broker_us_id
							? customsBrokers.find((cb) => cb.id === formData.customs_broker_us_id)?.name ||
								'Selecciona...'
							: 'Selecciona...'}
					</span>
				</Select.Trigger>
				<Select.Content class="max-h-[300px]">
					{#each customsBrokers as broker}
						<Select.Item value={broker.id.toString()}>
							{broker.name}
						</Select.Item>
					{/each}
				</Select.Content>
			</Select.Root>
		</div>
	</div>

	<!-- Columna Derecha: Tipo de Moneda y Transportista -->
	<div class="space-y-3">
		<!-- Tipo de Moneda - Pesos Netos y Brutos -->
		<div class="border rounded-md p-3 space-y-2">
			<div class="flex justify-between">
				<h4 class="text-xs font-semibold text-muted-foreground uppercase">
					Tipo de Moneda - Pesos Netos y Brutos
				</h4>
				<h4 class="text-xs font-semibold text-muted-foreground uppercase">
					Tipo de cambio:
					<span class="text-primary ml-1">
						{exchangeRate !== undefined && exchangeRate !== null
							? exchangeRate === 0
								? 'N/A'
								: Number(exchangeRate).toFixed(4)
							: formData.exchange_rate
								? Number(formData.exchange_rate).toFixed(4)
								: 'N/A'}
					</span>
				</h4>
			</div>

			<!-- Radio buttons para tipo de moneda -->
			<div class="space-y-1.5">
				<RadioGroup.Root bind:value={formData.currency} class="flex gap-4">
					<div class="flex items-center space-x-2">
						<RadioGroup.Item value="foreign" id="currency-foreign" class="h-4 w-4" />
						<Label for="currency-foreign" class="text-xs font-normal cursor-pointer"
							>Extranjera (Dlls)</Label
						>
					</div>
					<div class="flex items-center space-x-2">
						<RadioGroup.Item value="local" id="currency-local" class="h-4 w-4" />
						<Label for="currency-local" class="text-xs font-normal cursor-pointer"
							>Nacional (Pesos)</Label
						>
					</div>
					<div class="flex items-center space-x-2">
						<RadioGroup.Item value="manual" id="currency-manual" class="h-4 w-4" />
						<Label for="currency-manual" class="text-xs font-normal cursor-pointer"
							>De Captura</Label
						>
					</div>
				</RadioGroup.Root>
			</div>
			{#if formData.currency === 'manual'}
				<div class="space-y-1.5">
					<Label for="currency_type" class="text-xs">Moneda:</Label>
					<Select.Root
						type="single"
						value={formData.currency_type || ''}
						onValueChange={(v) => {
							formData.currency_type = v ?? '';
						}}
					>
						<Select.Trigger id="currency_type" class="h-7 text-xs min-w-[80px]">
							<span class="truncate">
								{formData.currency_type || '...'}
							</span>
						</Select.Trigger>
						<Select.Content class="min-w-[80px] max-h-[300px]">
							{#each currencyTypes as currencyType}
								<Select.Item value={currencyType.code}>
									{currencyType.code}
								</Select.Item>
							{/each}
						</Select.Content>
					</Select.Root>
				</div>
			{/if}
			<div class="grid grid-cols-3 gap-2">
				<div class="space-y-1.5">
					<Label for="weight_type" class="text-xs">Tipo Peso:</Label>
					<Select.Root
						type="single"
						value={formData.weight_type || 'kgs'}
						onValueChange={(v) => {
							formData.weight_type = v ?? 'kgs';
						}}
					>
						<Select.Trigger id="weight_type" class="min-w-[150px] h-7 text-xs">
							<span class="truncate">
								{weightTypeOptions.find((w) => w.value === formData.weight_type)?.label ||
									'Kilogramos (kg)'}
							</span>
						</Select.Trigger>
						<Select.Content>
							{#each weightTypeOptions as weightType}
								<Select.Item value={weightType.value}>
									{weightType.label}
								</Select.Item>
							{/each}
						</Select.Content>
					</Select.Root>
				</div>

				{#if operationType !== 1 && invoiceType !== 'MEX' && invoiceType !== 'CR' && invoiceType !== 'REP' && invoiceType !== 'REPAR'}
					<div class="space-y-1.5">
						<Label for="iva_factor" class="text-xs">IVA:</Label>
						<Input
							id="iva_factor"
							type="number"
							step="0.0001"
							bind:value={formData.iva_factor}
							placeholder="0.16"
							class="h-7 text-xs"
						/>
					</div>
				{/if}
				{#if operationType === 1 || invoiceType === 'CR'}
					<div class="space-y-1.5">
						<Label for="manifest_number" class="text-xs">Num. de Manifiesto:</Label>
						<div class="flex gap-2">
							<Input
								id="manifest_number"
								bind:value={formData.manifest_number}
								placeholder="Manifiesto..."
								class="h-7 flex-1 text-xs"
							/>
							<Button
								variant="outline"
								size="icon"
								class="h-7 w-7"
								onclick={() => (showManifestModal = true)}
							>
								<Search class="h-3.5 w-3.5" />
							</Button>
						</div>
					</div>
				{/if}
			</div>
		</div>

		<!-- Transportista -->
		<div class="border rounded-md p-3 space-y-2">
			<h4 class="text-xs font-semibold text-muted-foreground uppercase">Transportista</h4>

			<div class="grid grid-cols-3 gap-2">
				{#if invoiceType !== 'MEX'}
					<div class="space-y-1.5">
						<Label for="carrier_id" class="text-xs">Transportista:</Label>
						<Select.Root
							type="single"
							value={formData.carrier_id ? String(formData.carrier_id) : ''}
							onValueChange={(v) => {
								formData.carrier_id = v || null;
							}}
						>
							<Select.Trigger id="carrier_id" class="h-7 text-xs min-w-[120px] max-w-[250px]">
								<span class="truncate">
									{#if formData.carrier_id}
										{transporters.find(
											(t) => String(t.transporter_key) === String(formData.carrier_id)
										)?.name || formData.carrier_id}
									{:else if transporters.length > 0}
										Selecciona transportista...
									{:else}
										Sin datos
									{/if}
								</span>
							</Select.Trigger>
							<Select.Content class="max-h-[300px]">
								{#each transporters as transporter}
									<Select.Item value={String(transporter.transporter_key)}>
										{transporter.transporter_key}
									</Select.Item>
								{/each}
							</Select.Content>
						</Select.Root>
					</div>
				{/if}

				<div class="col-span-2 space-y-1.5">
					<Label for="transport_id" class="text-xs">Clave Transporte:</Label>
					<Select.Root
						type="single"
						value={formData.transport_id || ''}
						onValueChange={(v) => {
							formData.transport_id = v ?? '';
						}}
					>
						<Select.Trigger id="transport_id" class="h-7 max-w-[250px] min-w-[120px] text-xs">
							<span class="truncate">
								{#if formData.transport_id}
									{vehicles.find((v) => v.vehicle_key === formData.transport_id)?.vehicle_key ||
										formData.transport_id}
								{:else if vehicles.length > 0}
									Selecciona vehículo...
								{:else}
									Sin datos
								{/if}
							</span>
						</Select.Trigger>
						<Select.Content class="max-h-[300px]">
							{#each vehicles as vehicle}
								<Select.Item value={vehicle.vehicle_key}>
									{vehicle.vehicle_key}
									{vehicle.plate_number ? `- ${vehicle.plate_number}` : ''}
								</Select.Item>
							{/each}
						</Select.Content>
					</Select.Root>
				</div>
			</div>

			<div class="space-y-1.5">
				<Label for="driver_name" class="text-xs">Conductor:</Label>
				<Select.Root
					type="single"
					value={formData.driver_name || ''}
					onValueChange={(v) => {
						formData.driver_name = v ?? '';
					}}
				>
					<Select.Trigger id="driver_name" class="h-7 w-full text-xs">
						<span class="truncate">
							{#if formData.driver_name}
								{formData.driver_name}
							{:else if drivers.length > 0}
								Selecciona conductor...
							{:else}
								Sin datos
							{/if}
						</span>
					</Select.Trigger>
					<Select.Content class="max-h-[300px]">
						{#each drivers as driver}
							<Select.Item value={driver.driver_name}>
								{driver.driver_name}
							</Select.Item>
						{/each}
					</Select.Content>
				</Select.Root>
			</div>

			<div class="grid grid-cols-4 gap-2">
				<div class="space-y-1.5">
					<Label for="transport_type" class="text-xs">Tipo Transporte:</Label>
					<Select.Root
						type="single"
						value={formData.transport_type || 'none'}
						onValueChange={(v) => {
							formData.transport_type = v ?? 'none';
						}}
					>
						<Select.Trigger id="transport_type" class="h-7 max-w-[250px] min-w-[120px] text-xs">
							<span class="truncate">
								{transportTypeOptions.find((t) => t.value === formData.transport_type)?.label ||
									'Ninguno'}
							</span>
						</Select.Trigger>
						<Select.Content>
							{#each transportTypeOptions as option}
								<Select.Item value={option.value}>
									{option.label}
								</Select.Item>
							{/each}
						</Select.Content>
					</Select.Root>
				</div>

				<div class="col-span-3 space-y-1.5">
					<Label for="transport_num" class="text-xs">Placas:</Label>
					<Select.Root
						type="single"
						value={formData.transport_num || ''}
						onValueChange={(v) => {
							formData.transport_num = v ?? '';
						}}
					>
						<Select.Trigger id="transport_num" class="h-7 w-full text-xs">
							<span class="truncate">
								{#if formData.transport_num}
									{trailers.find((t) => t.trailer_number === formData.transport_num)
										?.plate_number || formData.transport_num}
								{:else if trailers.length > 0}
									Selecciona remolque...
								{:else}
									Sin datos
								{/if}
							</span>
						</Select.Trigger>
						<Select.Content class="max-h-[300px]">
							{#each trailers as trailer}
								<Select.Item value={trailer.trailer_number}>
									{trailer.plate_number || trailer.trailer_number}
								</Select.Item>
							{/each}
						</Select.Content>
					</Select.Root>
				</div>
			</div>

			{#if invoiceType !== 'MEX'}
				<div class="space-y-1.5">
					<Label for="aduana" class="text-xs">Aduana y Sección de Despacho:</Label>
					<Select.Root
						type="single"
						value={formData.aduana || ''}
						onValueChange={(v) => {
							formData.aduana = v ?? '';
						}}
					>
						<Select.Trigger id="aduana" class="h-7 text-xs w-full">
							<span class="truncate">
								{#if formData.aduana}
									{customsSections.find((cs) => cs.customs_code === formData.aduana)
										?.section_name || formData.aduana}
								{:else if customsSections.length > 0}
									Selecciona aduana...
								{:else}
									Sin datos
								{/if}
							</span>
						</Select.Trigger>
						<Select.Content class="max-h-[300px]">
							{#each customsSections as section}
								<Select.Item value={section.customs_code}>
									{section.customs_code} - {section.section_name}
								</Select.Item>
							{/each}
						</Select.Content>
					</Select.Root>
				</div>
			{/if}

			{#if invoiceType !== 'MEX'}
				<div class="space-y-1.5">
					<Label for="document_type" class="text-xs"
						>Clave de Régimen Aduanero: <span class="text-red-500">*</span></Label
					>
					<Select.Root
						type="single"
						value={formData.document_type || ''}
						onValueChange={(v) => {
							formData.document_type = v ?? '';
						}}
					>
						<Select.Trigger id="document_type" class="h-7 text-xs w-full">
							<span class="truncate">
								{#if formData.document_type}
									{codePedimentoRegimens.find((r) => r.regimen_code === formData.document_type)
										?.regimen_code || formData.document_type}
								{:else if filteredRegimens.length > 0}
									Selecciona régimen...
								{:else if operationType}
									Sin regímenes para tipo {operationType}
								{:else}
									Selecciona tipo de operación primero
								{/if}
							</span>
						</Select.Trigger>
						<Select.Content class="max-h-[300px]">
							{#each filteredRegimens as regimen}
								<Select.Item value={regimen.regimen_code}>
									{regimen.regimen_code}
								</Select.Item>
							{/each}
						</Select.Content>
					</Select.Root>
				</div>
			{/if}

			{#if invoiceType === 'MEX'}
				<div class="space-y-1.5 pt-1">
					<Label for="electronic-sig-gen" class="text-xs">Firma Electrónica:</Label>
					<div class="flex gap-2">
						<Input
							id="electronic-sig-gen"
							bind:value={formData.code_signature}
							class="h-7 flex-1 text-xs"
						/>
						<Button variant="outline" size="icon" class="h-7 w-7">
							<Upload class="h-3 w-3" />
						</Button>
					</div>
				</div>
			{/if}
		</div>
	</div>
</div>

<ManifestSelectorModal bind:open={showManifestModal} onSelect={handleManifestSelect} />
