<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 { m } from '$lib/i18n/messages';
	import { cn } from '$lib/utils';
	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 { displayCustomsBrokerLabel, 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,
		isSettings = false,
		highlightFieldId = null,
		onDismissHighlightForField = 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;
		isSettings?: boolean;
		highlightFieldId?: string | null;
		onDismissHighlightForField?: (fieldKey: string) => void;
	} = $props();

	function hl(id: string) {
		return cn(highlightFieldId === id && 'ring-2 ring-destructive ring-offset-2 rounded-md');
	}

	function snapshotValueForHighlight(fd: any, key: string): unknown {
		if (!fd) return undefined;
		if (key === 'currency-foreign') return fd.currency;
		switch (key) {
			case 'provider_header':
				return fd.provider_header;
			case 'provider_id':
				return fd.provider_id;
			case 'sold_to_header':
				return fd.sold_to_header;
			case 'sold_to_id':
				return fd.sold_to_id;
			case 'shipped_to_header':
				return fd.shipped_to_header;
			case 'shipped_to_id':
				return fd.shipped_to_id;
			case 'customs_broker_id':
				return fd.customs_broker_id;
			case 'customs_broker_us_id':
				return fd.customs_broker_us_id;
			case 'currency_type':
				return fd.currency_type;
			case 'weight_type':
				return fd.weight_type;
			case 'iva_factor':
				return fd.iva_factor;
			case 'manifest_number':
				return fd.manifest_number;
			case 'carrier_id':
				return fd.carrier_id;
			case 'transport_id':
				return fd.transport_id;
			case 'driver_name':
				return fd.driver_name;
			case 'transport_type':
				return fd.transport_type;
			case 'trailer_num':
				return fd.trailer_num;
			case 'aduana':
				return fd.aduana;
			case 'document_type':
				return fd.document_type;
			default:
				return fd[key];
		}
	}

	let generalHighlightSnapshot = $state<{ key: string; val: unknown } | null>(null);

	$effect(() => {
		const key = highlightFieldId;
		if (!key || !formData) {
			generalHighlightSnapshot = null;
			return;
		}
		const now = snapshotValueForHighlight(formData, key);
		if (!generalHighlightSnapshot || generalHighlightSnapshot.key !== key) {
			generalHighlightSnapshot = { key, val: now };
			return;
		}
		const same =
			JSON.stringify(now) === JSON.stringify(generalHighlightSnapshot.val) ||
			String(now ?? '') === String(generalHighlightSnapshot.val ?? '');
		if (!same) {
			onDismissHighlightForField?.(key);
			generalHighlightSnapshot = null;
		}
	});

	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,
				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 || '',
				trailer_num: invoice.logistics?.trailer_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,
				weight_type: 'kgs',
				iva_factor: null,
				carrier_id: null,
				transport_id: '',
				driver_name: '',
				transport_type: '',
				trailer_num: '',
				aduana: '',
				document_type: '',
				manifest_number: '',
				code_signature: '',
				electronic_signature: ''
			};
		}
	} 

	$effect.pre(() => {
		if (formData) {
			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 = '';

			// Migración de transport_num a trailer_num (Upstream change)
			if (formData.trailer_num === undefined && (formData as any).transport_num) {
				formData.trailer_num = (formData as any).transport_num;
				delete (formData as any).transport_num;
			}
			if (formData.trailer_num === undefined) formData.trailer_num = '';
		}
	});

	// Opciones de tipo de peso
	const weightTypeOptions = $derived.by(() => [
		{ value: 'kgs', label: m.invoice_edit_general_weight_type_kgs() },
		{ value: 'lbs', label: m.invoice_edit_general_weight_type_lbs() }
	]);

	// Opciones de tipo de transporte
	const transportTypeOptions = $derived.by(() => [
		{ value: 'none', label: m.invoice_edit_general_transport_none() },
		{ value: 'transport', label: m.invoice_edit_general_transport_type_transport() },
		{ value: 'box', label: m.invoice_edit_general_transport_type_box() },
		{ value: 'licence_plates', label: m.invoice_edit_general_transport_type_licence_plates() },
		{ value: 'truck', label: m.invoice_edit_general_transport_type_truck() },
		{ value: 'vessel', label: m.invoice_edit_general_transport_type_vessel() },
		{ value: 'rail_barge', label: m.invoice_edit_general_transport_type_rail_barge() },
		{ value: 'container', label: m.invoice_edit_general_transport_type_container() },
		{ value: 'airplane', label: m.invoice_edit_general_transport_type_airplane() },
		{ value: 'gondola', label: m.invoice_edit_general_transport_type_gondola() },
		{ value: 'flatbed', label: m.invoice_edit_general_transport_type_flatbed() }
	]);

	// Opciones de encabezados
	const providerHeaderOptions = $derived.by(() => [
		{ value: 'proveedor', label: m.invoice_edit_general_provider_header_supplier() },
		{ value: 'exportador', label: m.invoice_edit_general_provider_header_exporter() }
	]);

	const soldToHeaderOptions = $derived([
		{ value: 'consignado_a', label: m.invoice_edit_general_sold_to_header_consignado() },
		{ value: 'vendido_a', label: m.invoice_edit_general_sold_to_header_vendido() },
		{
			value: operationType === 1 ? 'exportado_a' : 'importador',
			label: operationType === 1 ? m.invoice_edit_general_sold_to_header_exportado() : m.invoice_edit_general_sold_to_header_importador()
		}
	]);

	const shippedToHeaderOptions = $derived(
		operationType === 1 || invoiceType === 'CR'
			? [
					{ value: 'enviado_a', label: m.invoice_edit_general_shipped_to_header_enviado() },
					{ value: 'transferido_a', label: m.invoice_edit_general_shipped_to_header_transferido() },
					{ value: 'donado_a', label: m.invoice_edit_general_shipped_to_header_donado() },
					{ value: 'importador', label: m.invoice_edit_general_sold_to_header_importador() }
				]
			: [
					{ value: 'enviado_a', label: m.invoice_edit_general_shipped_to_header_enviado() },
					{ value: 'transferido_a', label: m.invoice_edit_general_shipped_to_header_transferido() }
				]
	);

	/** Conductores del transportista elegido (evita opciones inválidas ante validate_common). */
	const driversForCarrier = $derived.by(() => {
		if (invoiceType === 'MEX') {
			return drivers;
		}
		const cid =
			formData.carrier_id !== null && formData.carrier_id !== undefined
				? String(formData.carrier_id).trim()
				: '';
		if (!cid) {
			return [];
		}
		return drivers.filter((d) => String(d.transporter_key) === cid);
	});

	$effect(() => {
		if (invoiceType === 'MEX') {
			return;
		}
		const cid =
			formData.carrier_id !== null && formData.carrier_id !== undefined
				? String(formData.carrier_id).trim()
				: '';
		if (!cid) {
			if (formData.driver_name) {
				formData.driver_name = '';
			}
			if (formData.trailer_num) {
				formData.trailer_num = '';
			}
			return;
		}
		if (!drivers.length) {
			return;
		}
		if (formData.driver_name) {
			const ok = drivers.some(
				(d) =>
					String(d.transporter_key) === cid && d.driver_name === formData.driver_name
			);
			if (!ok) {
				formData.driver_name = '';
			}
		}
	});

	const shippedByHeaderOptions = $derived(
		operationType === 1 || invoiceType === 'CR'
			? [
					{ value: 'enviado_por', label: m.invoice_edit_general_shipped_by_header_enviado_por() },
					{ value: 'destinatario', label: m.invoice_edit_general_shipped_by_header_destinatario() },
					{ value: 'vendido_por', label: m.invoice_edit_general_shipped_by_header_vendido_por() },
					{ value: 'consignado_a', label: m.invoice_edit_general_sold_to_header_consignado() },
					{ value: 'vendido_a', label: m.invoice_edit_general_sold_to_header_vendido() },
					{ value: 'exportado_a', label: m.invoice_edit_general_sold_to_header_exportado() },
					{ value: 'enviado_a', label: m.invoice_edit_general_shipped_to_header_enviado() },
					{ value: 'transferido_a', label: m.invoice_edit_general_shipped_to_header_transferido() },
					{ value: 'donado_a', label: m.invoice_edit_general_shipped_to_header_donado() },
					{ value: 'notificar_a', label: m.invoice_edit_general_shipped_by_header_notificar() }
				]
			: [
					{ value: 'enviado_a', label: m.invoice_edit_general_shipped_to_header_enviado() },
					{ value: 'transferido_a', label: m.invoice_edit_general_shipped_to_header_transferido() }
				]
	);

	// 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-1 gap-4 md:grid-cols-2">
	<!-- 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">{m.invoice_edit_general_pedimento_section()}</h4>
			<div class="grid grid-cols-2 gap-3 text-xs md:grid-cols-4">
				<div>
						<span class="text-muted-foreground">{m.invoice_edit_general_pedimento_date_from()}</span>
					<p class="font-medium">{formData.fecha_pedimento_del || '-'}</p>
				</div>
				<div>
						<span class="text-muted-foreground">{m.invoice_edit_general_pedimento_date_to()}</span>
					<p class="font-medium">{formData.fecha_pedimento_al || '-'}</p>
				</div>
				<div>
						<span class="text-muted-foreground">{m.invoice_edit_general_pedimento_code()}</span>
					<p class="font-medium">{formData.clave_pedimento || '-'}</p>
				</div>
				<div>
						<span class="text-muted-foreground">{m.invoice_edit_general_pedimento_regimen()}</span>
					<p class="font-medium">{formData.regimen_pedimento || '-'}</p>
				</div>
			</div>
		{/if}

			<h4 class="text-xs font-semibold text-muted-foreground uppercase">
				{m.invoice_edit_general_clients_suppliers_broker()}
			</h4>
		<div class="grid min-w-0 grid-cols-[1fr_4fr_4fr] items-center gap-x-2 gap-y-2">
			<!-- Row 1: Proveedor / Exportador -->
			<Select.Root
				type="single"
				value={formData.provider_header || providerHeaderOptions[0]?.value || ''}
				onValueChange={(v) => {
					formData.provider_header = v ?? '';
				}}
			>
				<Select.Trigger id="provider_header" class={cn('h-7 w-full text-xs', hl('provider_header'))}>
					<span class="truncate">
						{providerHeaderOptions.find(
							(o) => o.value === (formData.provider_header || providerHeaderOptions[0]?.value)
						)?.label || m.invoice_edit_general_select_header_placeholder()}
					</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={cn('h-7 w-full text-xs', hl('provider_id'))}>
					<span class="truncate">
						{#if formData.provider_id}
							{providers.find((p) => p.id === formData.provider_id)?.name || m.invoice_edit_general_select_placeholder()}
						{:else}
							{m.invoice_edit_general_select_placeholder()}
						{/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>
			{#if !isSettings}<span class="font-bold text-red-500">*</span>{/if}

			<!-- Row 2: Consignado a / Vendido a / Importador -->
			<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={cn('h-7 w-full text-xs', hl('sold_to_header'))}>
					<span class="truncate">
						{soldToHeaderOptions.find(
							(o) => o.value === (formData.sold_to_header || soldToHeaderOptions[0]?.value)
						)?.label || m.invoice_edit_general_select_header_placeholder()}
					</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={cn('h-7 w-full text-xs', hl('sold_to_id'))}>
					<span class="truncate">
						{#if formData.sold_to_id}
							{clients.find((c) => c.id === formData.sold_to_id)?.name || m.invoice_edit_general_select_placeholder()}
						{:else}
							{m.invoice_edit_general_select_placeholder()}
						{/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>
			{#if !isSettings}<span class="font-bold text-red-500">*</span>{/if}

			<!-- Row 3: Enviado a -->
			<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={cn('h-7 w-full text-xs', hl('shipped_to_header'))}>
					<span class="truncate">
						{shippedToHeaderOptions.find(
							(o) => o.value === (formData.shipped_to_header || shippedToHeaderOptions[0]?.value)
						)?.label || m.invoice_edit_general_select_header_placeholder()}
					</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={cn('h-7 w-full text-xs', hl('shipped_to_id'))}>
					<span class="truncate">
						{#if formData.shipped_to_id}
							{allClientsProviders.find((cp) => cp.id === formData.shipped_to_id)?.name ||
								m.invoice_edit_general_select_placeholder()}
						{:else}
							{m.invoice_edit_general_select_placeholder()}
						{/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>
			{#if !isSettings}<span class="font-bold text-red-500">*</span>{/if}
		</div>

		<div class="space-y-1.5">
			<Label for="customs_broker_id" class="text-xs"
					>{m.invoice_edit_general_broker_mex_label()} {#if !isSettings}<span class="text-red-500">*</span>{/if}</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={cn('h-7 max-w-[300px] min-w-[150px] text-xs', hl('customs_broker_id'))}
				>
					<span class="truncate">
						{#if formData.customs_broker_id}
							{@const selMex = customsBrokers.find((cb) => cb.id === formData.customs_broker_id)}
							{selMex
								? displayCustomsBrokerLabel(selMex)
								: `#${formData.customs_broker_id}`}
						{:else}
							{m.invoice_edit_general_select_broker_placeholder()}
						{/if}
					</span>
				</Select.Trigger>
				<Select.Content class="max-h-[300px]">
					{#each customsBrokers as broker}
						<Select.Item value={broker.id.toString()}>
							{displayCustomsBrokerLabel(broker)}
						</Select.Item>
					{/each}
				</Select.Content>
			</Select.Root>
		</div>

		<div class="space-y-1.5">
				<Label for="customs_broker_us_id" class="text-xs">{m.invoice_edit_general_broker_usa_label()}</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={cn(' h-7 min-w-[150px] text-xs', hl('customs_broker_us_id'))}>
					<span class="truncate">
						{#if formData.customs_broker_us_id}
							{@const selUs = customsBrokers.find((cb) => cb.id === formData.customs_broker_us_id)}
							{selUs
								? displayCustomsBrokerLabel(selUs)
								: `#${formData.customs_broker_us_id}`}
						{:else}
							{m.invoice_edit_general_select_broker_placeholder()}
						{/if}
					</span>
				</Select.Trigger>
				<Select.Content class="max-h-[300px]">
					{#each customsBrokers as broker}
						<Select.Item value={broker.id.toString()}>
							{displayCustomsBrokerLabel(broker)}
						</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="space-y-2 rounded-md border p-3">
			<div class="flex flex-wrap justify-between gap-1">
				<h4 class="text-xs font-semibold text-muted-foreground uppercase">
					{m.invoice_edit_general_currency_weight_section()}
				</h4>
				<h4 class="text-xs font-semibold text-muted-foreground uppercase">
					{m.invoice_edit_general_exchange_rate()}
					<span class="ml-1 text-primary">
						{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 flex-wrap gap-x-4 gap-y-2">
					<div class="flex items-center space-x-2">
						<RadioGroup.Item
							value="foreign"
							id="currency-foreign"
							class={cn('h-4 w-4', hl('currency-foreign'))}
						/>
						<Label for="currency-foreign" class="cursor-pointer text-xs font-normal"
							>{m.invoice_edit_general_currency_foreign()}</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="cursor-pointer text-xs font-normal"
							>{m.invoice_edit_general_currency_local()}</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="cursor-pointer text-xs font-normal"
							>{m.invoice_edit_general_currency_manual()}</Label
						>
					</div>
				</RadioGroup.Root>
			</div>
			{#if formData.currency === 'manual'}
				<div class="space-y-1.5">
					<Label for="currency_type" class="text-xs">{m.invoice_edit_general_currency_label()}</Label>
					<Select.Root
						type="single"
						value={formData.currency_type || ''}
						onValueChange={(v) => {
							formData.currency_type = v ?? '';
						}}
					>
						<Select.Trigger id="currency_type" class={cn('h-7 min-w-[80px] text-xs', hl('currency_type'))}>
							<span class="truncate">
								{formData.currency_type || '...'}
							</span>
						</Select.Trigger>
						<Select.Content class="max-h-[300px] min-w-[80px]">
							{#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-1 gap-2 sm:grid-cols-3">
				<div class="space-y-1.5">
					<Label for="weight_type" class="text-xs">{m.invoice_edit_general_weight_type_label()}</Label>
					<Select.Root
						type="single"
						value={formData.weight_type || 'kgs'}
						onValueChange={(v) => {
							formData.weight_type = v ?? 'kgs';
						}}
					>
						<Select.Trigger id="weight_type" class={cn('h-7 min-w-[150px] text-xs', hl('weight_type'))}>
							<span class="truncate">
								{weightTypeOptions.find((w) => w.value === formData.weight_type)?.label ||
									m.invoice_edit_general_weight_type_kgs()}
							</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">{m.invoice_edit_general_iva_label()}</Label>
						<Input
							id="iva_factor"
							type="number"
							step="0.0001"
							bind:value={formData.iva_factor}
							placeholder="0.16"
							class={cn('h-7 text-xs', hl('iva_factor'))}
						/>
					</div>
				{/if}
				{#if operationType === 1 || invoiceType === 'CR'}
					<div class="space-y-1.5">
						<Label for="manifest_number" class="text-xs">{m.invoice_edit_general_manifest_number_label()}</Label>
						<div class="flex gap-2">
							<Input
								id="manifest_number"
								bind:value={formData.manifest_number}
								placeholder="Manifiesto..."
								class={cn('h-7 flex-1 text-xs', hl('manifest_number'))}
							/>
							<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="space-y-2 rounded-md border p-3">
			<h4 class="text-xs font-semibold text-muted-foreground uppercase">{m.invoice_edit_general_transport_section()}</h4>

			<div class="grid grid-cols-1 gap-2 sm:grid-cols-3">
				{#if invoiceType !== 'MEX'}
					<div class="space-y-1.5">
						<Label for="carrier_id" class="text-xs">{m.invoice_edit_general_transport_label()}</Label>
						<Select.Root
							type="single"
							value={formData.carrier_id ? String(formData.carrier_id) : ''}
							onValueChange={(v) => {
								formData.carrier_id = v || null;
								formData.driver_name = '';
								formData.trailer_num = '';
							}}
						>
							<Select.Trigger id="carrier_id" class={cn('h-7 max-w-[250px] min-w-[120px] text-xs', hl('carrier_id'))}>
								<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}
										{m.invoice_edit_general_select_transporter_placeholder()}
									{:else}
										{m.invoice_edit_general_no_data()}
									{/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">{m.invoice_edit_general_transport_key_label()}</Label>
					<Select.Root
						type="single"
						value={formData.transport_id || ''}
						onValueChange={(v) => {
							formData.transport_id = v ?? '';
						}}
					>
						<Select.Trigger id="transport_id" class={cn('h-7 max-w-[250px] min-w-[120px] text-xs', hl('transport_id'))}>
							<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}
									{m.invoice_edit_general_select_vehicle_placeholder()}
								{:else}
									{m.invoice_edit_general_no_data()}
								{/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">{m.invoice_edit_general_driver_label()}</Label>
				<Select.Root
					type="single"
					value={formData.driver_name || ''}
					disabled={invoiceType !== 'MEX' &&
						(!formData.carrier_id || driversForCarrier.length === 0)}
					onValueChange={(v) => {
						formData.driver_name = v ?? '';
					}}
				>
					<Select.Trigger id="driver_name" class={cn('h-7 w-full text-xs', hl('driver_name'))}>
						<span class="truncate">
							{#if formData.driver_name}
								{formData.driver_name}
							{:else if invoiceType !== 'MEX' && !formData.carrier_id}
								{m.invoice_edit_general_choose_transporter_first()}
							{:else if invoiceType !== 'MEX' && driversForCarrier.length === 0}
								{m.invoice_edit_general_no_drivers_for_transporter()}
							{:else if driversForCarrier.length > 0}
								{m.invoice_edit_general_select_driver_placeholder()}
							{:else}
								{m.invoice_edit_general_no_data()}
							{/if}
						</span>
					</Select.Trigger>
					<Select.Content class="max-h-[300px]">
						{#each driversForCarrier as driver}
							<Select.Item value={driver.driver_name ?? ''}>
								{driver.driver_name}
							</Select.Item>
						{/each}
					</Select.Content>
				</Select.Root>
			</div>

			<div class="grid grid-cols-2 gap-2 sm:grid-cols-4">
				<div class="space-y-1.5">
					<Label for="transport_type" class="text-xs">{m.invoice_edit_general_transport_type_label()}</Label>
					<Select.Root
						type="single"
						value={formData.transport_type || 'none'}
						onValueChange={(v) => {
							formData.transport_type = v ?? 'none';
						}}
					>
						<Select.Trigger id="transport_type" class={cn('h-7 max-w-[250px] min-w-[120px] text-xs', hl('transport_type'))}>
							<span class="truncate">
								{transportTypeOptions.find((t) => t.value === formData.transport_type)?.label ||
									m.invoice_edit_general_transport_none()}
							</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-1 space-y-1.5 sm:col-span-3">
					<Label for="trailer_num" class="text-xs">
						{m.invoice_edit_general_trailer_label()}:{#if (formData.transport_type || 'none') !== 'none'}
							<span class="text-red-500"> *</span>
						{/if}
					</Label>
					<Select.Root
						type="single"
						value={formData.trailer_num || ''}
						onValueChange={(v) => {
							formData.trailer_num = v ?? '';
						}}
					>
						<Select.Trigger id="trailer_num" class={cn('h-7 w-full text-xs', hl('trailer_num'))}>
							<span class="truncate">
								{#if formData.trailer_num}
									{trailers.find((t) => t.trailer_number === formData.trailer_num)?.plate_number ||
										formData.trailer_num}
								{:else if invoiceType !== 'MEX' && !formData.carrier_id}
									{m.invoice_edit_general_choose_transporter_first()}
								{:else if trailers.length > 0}
									{m.invoice_edit_general_select_trailer_placeholder()}
								{:else}
									{m.invoice_edit_general_no_data()}
								{/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">{m.invoice_edit_general_customs_label()} <span class="text-red-500">*</span></Label>
					<Select.Root
						type="single"
						value={formData.aduana || ''}
						onValueChange={(v) => {
							formData.aduana = v ?? '';
						}}
					>
						<Select.Trigger id="aduana" class={cn('h-7 w-full text-xs', hl('aduana'))}>
							<span class="truncate">
								{#if formData.aduana}
									{customsSections.find((cs) => cs.customs_code === formData.aduana)
										?.section_name || formData.aduana}
								{:else if customsSections.length > 0}
									{m.invoice_edit_general_select_customs_placeholder()}
								{:else}
									{m.invoice_edit_general_no_data()}
								{/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"
						>{m.invoice_edit_general_document_type_label()} <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={cn('h-7 w-full text-xs', hl('document_type'))}>
							<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}
									{m.invoice_edit_general_select_regimen_placeholder()}
								{:else if operationType}
									{m.invoice_edit_general_no_regimens_for_operation()} {operationType}
								{:else}
									{m.invoice_edit_general_choose_operation_first()}
								{/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">{m.invoice_edit_general_signature_label()}</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} />
