<script lang="ts">
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Checkbox } from '$lib/components/ui/checkbox';
	import { RadioGroup, RadioGroupItem } from '$lib/components/ui/radio-group';
	import { Button } from '$lib/components/ui/button';
	import { Search } from 'lucide-svelte';
	import { m } from '$lib/i18n/messages';
	import PortSelectorModal from './PortSelectorModal.svelte';
	import type { Invoice } from '$lib/api/dashboard/a76/invoices';

	let {
		invoice,
		formData = $bindable(),
		exists = $bindable(),
		operationType = undefined,
		invoiceType = undefined,
		isSettings = false
	}: {
		invoice: Invoice | null;
		formData?: any;
		exists?: boolean;
		operationType?: number;
		invoiceType?: string;
		isSettings?: boolean;
	} = $props();

	if (!formData && invoice) {
		formData = {
			// Campos de esta pestaña
			numero_tipo_transporte:
				invoice.logistics?.trailer_num || invoice.logistics?.transport_num || invoice.logistics?.vehicle_num || '',
			es_ferrocarril: invoice.logistics?.is_rail ? 'si' : 'no',
			numero_bl: invoice.logistics?.bill_number || '',
			cantidad_guias_embarque: invoice.logistics?.guide_number || null,
			destino_origen: invoice.logistics?.destination_location || '',
			puerto_entrada: invoice.logistics?.origin_location || '',
			vehicle_data: invoice.logistics?.vehicle_data || '',
			// Checkboxes
			fue_revisado_equipo: invoice.logistics?.equipment_reviewed || false,
			sub_division: invoice.logistics?.is_subdivision || false,
			funge_como_cd: invoice.logistics?.acts_as_cd || false,
			llego_pedimento: invoice.logistics?.pedimento_arrived || false,
			// Errores
			errores_facturacion: [],
			// Semáforos
			semaforo_verde_aduana_mexicana: invoice.logistics?.green_light_mx || false,
			semaforo_verde_aduana_americana: invoice.logistics?.green_light_us || false,
			semaforo_rojo_aduana_mexicana: invoice.logistics?.red_light_mx || false,
			semaforo_rojo_aduana_americana: invoice.logistics?.red_light_us || false,
			// New Export fields
			is_mixed: invoice.compliance_mx?.is_mixed || false,
			reason_export: invoice.compliance_mx?.reason_export || '1',
			purchase_order: invoice.purchase_order || '',
			payment_terms: invoice.payment_terms || '',
			handling_fees: invoice.handling_fees || 0,
			cfdi_uuid: invoice.cfdi_uuid || '',
			path_pdf: invoice.path_pdf || '',
			path_xml: invoice.path_xml || ''
		};
		exists = true;
	} else if (!formData) {
		formData = {
			// Campos de esta pestaña
			numero_tipo_transporte: '',
			es_ferrocarril: 'no',
			numero_bl: '',
			cantidad_guias_embarque: null,
			destino_origen: '',
			puerto_entrada: '',
			vehicle_data: '',
			// Checkboxes
			fue_revisado_equipo: false,
			sub_division: false,
			funge_como_cd: false,
			llego_pedimento: false,
			// Errores
			errores_facturacion: [],
			// Semáforos
			semaforo_verde_aduana_mexicana: false,
			semaforo_verde_aduana_americana: false,
			semaforo_rojo_aduana_mexicana: false,
			semaforo_rojo_aduana_americana: false,
			// New Export fields
			is_mixed: false,
			reason_export: '1',
			purchase_order: '',
			payment_terms: '',
			handling_fees: 0,
			cfdi_uuid: '',
			path_pdf: '',
			path_xml: ''
		};
		exists = false;
	}

	$effect.pre(() => {
		if (formData) {
			if (formData.es_ferrocarril === undefined) formData.es_ferrocarril = 'no';
			if (formData.is_mixed === undefined) formData.is_mixed = false;
			if (formData.reason_export === undefined) formData.reason_export = '1';
			if (formData.fue_revisado_equipo === undefined) formData.fue_revisado_equipo = false;
			if (formData.sub_division === undefined) formData.sub_division = false;
			if (formData.funge_como_cd === undefined) formData.funge_como_cd = false;
			if (formData.llego_pedimento === undefined) formData.llego_pedimento = false;
			if (formData.semaforo_verde_aduana_mexicana === undefined) formData.semaforo_verde_aduana_mexicana = false;
			if (formData.semaforo_verde_aduana_americana === undefined) formData.semaforo_verde_aduana_americana = false;
			if (formData.semaforo_rojo_aduana_mexicana === undefined) formData.semaforo_rojo_aduana_mexicana = false;
			if (formData.semaforo_rojo_aduana_americana === undefined) formData.semaforo_rojo_aduana_americana = false;
		}
	});

	let showPortModal = $state(false);

	function handlePortSelect(section: any) {
		formData.puerto_entrada = section.customs_code;
	}
</script>

<!-- Layout de 2 columnas compacto -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
	<!-- Columna Izquierda -->
	<div class="space-y-3 rounded-md border p-3">
		<h4 class="text-xs font-semibold text-muted-foreground uppercase">{m['invoice_item_fa.continuation.general_info']()}</h4>

		<!-- NÚMERO/TIPO DE TRANSPORTE -->
		<div class="space-y-1.5">
			<Label for="numero_tipo_transporte" class="text-xs">{m['invoice_item_fa.continuation.transport_number_type']()}</Label>
			<Input
				id="numero_tipo_transporte"
				bind:value={formData.numero_tipo_transporte}
				class="h-7 text-xs"
			/>
		</div>

		<!-- DATOS VEHÍCULO -->
		<div class="space-y-2 rounded border bg-muted/30 p-2">
			<Label for="vehicle_data" class="text-xs font-semibold">{m['invoice_item_fa.continuation.vehicle_data']()}</Label>
			<Input id="vehicle_data" bind:value={formData.vehicle_data} class="mb-2 h-7 text-xs" />
			<div class="space-y-1.5">
				<Label class="text-xs">{m['invoice_item_fa.continuation.is_rail']()}</Label>
				<RadioGroup value={formData.es_ferrocarril} onValueChange={(v) => formData.es_ferrocarril = v} class="flex gap-4">
					<div class="flex items-center gap-2">
						<RadioGroupItem value="si" id="ferrocarril_si" />
						<Label for="ferrocarril_si" class="text-xs">{m['invoice_item_fa.continuation.yes']()}</Label>
					</div>
					<div class="flex items-center gap-2">
						<RadioGroupItem value="no" id="ferrocarril_no" />
						<Label for="ferrocarril_no" class="text-xs">{m['invoice_item_fa.continuation.no']()}</Label>
					</div>
				</RadioGroup>
			</div>
			<div class="space-y-1.5">
				<Label for="numero_bl" class="text-xs">{m['invoice_item_fa.continuation.bill_number']()}</Label>
				<Input id="numero_bl" bind:value={formData.numero_bl} class="h-7 text-xs" />
			</div>
			<div class="space-y-1.5">
				<Label for="cantidad_guias_embarque" class="text-xs"
					>{m['invoice_item_fa.continuation.guide_count']()}</Label
				>
				<Input
					id="cantidad_guias_embarque"
					type="number"
					bind:value={formData.cantidad_guias_embarque}
					class="h-7 text-xs"
				/>
			</div>
		</div>

		<!-- DESTINO/ORIGEN Y ES MIXTO -->
		<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
			<div class="space-y-1.5">
				<Label for="destino_origen" class="text-xs">{m['invoice_item_fa.continuation.destination_origin']()}</Label>
				<Input
					id="destino_origen"
					bind:value={formData.destino_origen}
					placeholder={m['invoice_item_fa.continuation.destination_origin_placeholder']()}
					class="h-7 text-xs"
				/>
			</div>

			{#if operationType === 1 || invoiceType === 'CR' || invoiceType === 'REP'}
				<div class="space-y-1.5">
						<Label class="text-xs">{m['invoice_item_fa.continuation.is_mixed']()}</Label>
					<RadioGroup 
						value={String(formData.is_mixed)} 
						onValueChange={(v: string | undefined) => (formData.is_mixed = v === 'true')}
						class="flex flex-wrap gap-4"
					>
						<div class="flex items-center gap-2">
							<RadioGroupItem value="true" id="mixed_si" />
							<Label for="mixed_si" class="text-xs text-muted-foreground">{m['invoice_item_fa.continuation.yes']()}</Label>
						</div>
						<div class="flex items-center gap-2">
							<RadioGroupItem value="false" id="mixed_no" />
							<Label for="mixed_no" class="text-xs text-muted-foreground">{m['invoice_item_fa.continuation.no']()}</Label>
						</div>
					</RadioGroup>
				</div>
			{/if}
		</div>

		{#if operationType !== 1 && invoiceType !== 'CR'}
			<div class="space-y-1.5">
				<Label for="puerto_entrada" class="text-xs">{m['invoice_item_fa.continuation.entry_port']()}</Label>
				<div class="flex gap-2">
					<Input
						id="puerto_entrada"
						bind:value={formData.puerto_entrada}
						class="h-7 flex-1 text-xs"
					/>
					<Button
						variant="outline"
						size="icon"
						class="h-7 w-7"
						onclick={() => (showPortModal = true)}
					>
						<Search class="h-3.5 w-3.5" />
					</Button>
				</div>
			</div>
		{/if}

		{#if operationType === 1 || invoiceType === 'CR'}
			<div class="space-y-3 pt-1">
				<div class="space-y-1.5 pt-4">
					<Label class="text-xs">{m['invoice_item_fa.continuation.export_reason']()}</Label>
					<RadioGroup value={formData.reason_export} onValueChange={(v) => formData.reason_export = v} class="flex flex-wrap gap-4">
						<div class="flex items-center space-x-2">
							<RadioGroupItem value="1" id="reason_vendido" />
							<Label for="reason_vendido" class="text-xs text-muted-foreground">{m['invoice_item_fa.continuation.reason_sold']()}</Label>
						</div>
						<div class="flex items-center gap-2">
							<RadioGroupItem value="2" id="reason_no_vendido" />
							<Label for="reason_no_vendido" class="text-xs text-muted-foreground">{m['invoice_item_fa.continuation.reason_not_sold']()}</Label
							>
						</div>
						<div class="flex items-center gap-2">
							<RadioGroupItem value="3" id="reason_otro" />
							<Label for="reason_otro" class="text-xs text-muted-foreground">{m['invoice_item_fa.continuation.reason_other']()}</Label>
						</div>
					</RadioGroup>
				</div>
				<div class="space-y-1.5">
					<Label for="purchase_order" class="text-xs">{m['invoice_item_fa.packages.purchase_order']()}:</Label>
					<Input id="purchase_order" bind:value={formData.purchase_order} class="h-7 text-xs" />
				</div>
				<div class="space-y-1.5">
					<Label for="payment_terms" class="text-xs">{m['invoice_item_fa.continuation.payment_terms']()}</Label>
					<Input id="payment_terms" bind:value={formData.payment_terms} class="h-7 text-xs" />
				</div>
				<div class="space-y-1.5">
					<Label for="handling_fees" class="text-xs">{m['invoice_item_fa.continuation.handling_fees']()}</Label>
					<div class="flex items-center gap-2">
						<Input
							id="handling_fees"
							type="number"
							bind:value={formData.handling_fees}
							class="h-7 flex-1 text-xs"
						/>
						<span class="text-[10px] font-bold text-muted-foreground">USD</span>
					</div>
				</div>
			</div>
		{/if}

		<!-- CHECKBOXES -->
		<div class="grid grid-cols-1 sm:grid-cols-2 gap-2">
			{#if operationType !== 1 && invoiceType !== 'CR'}
				<div class="flex items-center gap-2">
					<Checkbox id="fue_revisado" bind:checked={formData.fue_revisado_equipo} />
					<Label for="fue_revisado" class="text-xs">{m['invoice_item_fa.continuation.reviewed_equipment']()}</Label>
				</div>
				{#if invoiceType !== 'REP' && invoiceType !== 'REPAR'}
					<div class="flex items-center gap-2">
						<Checkbox id="sub_division" bind:checked={formData.sub_division} />
						<Label for="sub_division" class="text-xs">{m['invoice_item_fa.continuation.subdivision']()}</Label>
					</div>
					<div class="flex items-center gap-2">
						<Checkbox id="funge_como_cd" bind:checked={formData.funge_como_cd} />
						<Label for="funge_como_cd" class="text-xs">{m['invoice_item_fa.continuation.acts_as_cd']()}</Label>
					</div>
					<div class="flex items-center gap-2">
						<Checkbox id="llego_pedimento" bind:checked={formData.llego_pedimento} />
						<Label for="llego_pedimento" class="text-xs">{m['invoice_item_fa.continuation.pedimento_arrived']()}</Label>
					</div>
				{/if}
			{/if}
		</div>
	</div>

	<!-- Columna Derecha - Errores de Facturación -->
	<div class="space-y-3 rounded-md border p-3">
		<h4 class="text-xs font-semibold text-muted-foreground uppercase">{m['invoice_item_fa.continuation.billing_errors']()}</h4>

		<div class="rounded border">
			<table class="w-full text-xs">
				<thead class="bg-muted">
					<tr>
						<th class="border px-2 py-1 text-left">{m['invoice_item_fa.continuation.error_line']()}</th>
						<th class="border px-2 py-1 text-left">{m['invoice_item_fa.continuation.error_key']()}</th>
						<th class="border px-2 py-1 text-left">{m['invoice_item_fa.continuation.error_description']()}</th>
					</tr>
				</thead>
				<tbody>
					{#if formData.errores_facturacion?.length}
						{#each formData.errores_facturacion as error}
							<tr>
								<td class="border px-2 py-1">{error.linea}</td>
								<td class="border px-2 py-1">{error.clave}</td>
								<td class="border px-2 py-1">{error.descripcion}</td>
							</tr>
						{/each}
					{:else}
						<tr>
							<td colspan="3" class="border px-2 py-12 text-center text-muted-foreground">
								{m['invoice_item_fa.continuation.no_errors']()}
							</td>
						</tr>
					{/if}
				</tbody>
			</table>
		</div>

		<div class="flex justify-end gap-2">
			<Button variant="outline" size="sm" class="h-7 text-xs">{m['invoice_item_fa.continuation.insert']()}</Button>
			<Button variant="outline" size="sm" class="h-7 text-xs">{m['invoice_item_fa.continuation.edit']()}</Button>
			<Button variant="outline" size="sm" class="h-7 text-xs">{m['invoice_item_fa.continuation.delete']()}</Button>
		</div>

		<!-- SEMÁFORO -->
		<div class="space-y-2 rounded border bg-muted/30 p-2">
			<Label class="text-xs font-semibold">{m['invoice_item_fa.continuation.traffic_light']()}</Label>
			<div class="grid grid-cols-2 gap-2">
				<div class="flex items-center gap-2">
					<div class="h-2.5 w-2.5 rounded-full bg-green-500"></div>
					<Checkbox id="verde_mex" bind:checked={formData.semaforo_verde_aduana_mexicana} />
					<Label for="verde_mex" class="text-[10px]">{m['invoice_item_fa.continuation.green_mx']()}</Label>
				</div>
				<div class="flex items-center gap-2">
					<div class="h-2.5 w-2.5 rounded-full bg-green-600"></div>
					<Checkbox id="verde_usa" bind:checked={formData.semaforo_verde_aduana_americana} />
					<Label for="verde_usa" class="text-[10px]">{m['invoice_item_fa.continuation.green_usa']()}</Label>
				</div>
				<div class="flex items-center gap-2">
					<div class="h-2.5 w-2.5 rounded-full bg-red-500"></div>
					<Checkbox id="rojo_mex" bind:checked={formData.semaforo_rojo_aduana_mexicana} />
					<Label for="rojo_mex" class="text-[10px]">{m['invoice_item_fa.continuation.red_mx']()}</Label>
				</div>
				<div class="flex items-center gap-2">
					<div class="h-2.5 w-2.5 rounded-full bg-red-600"></div>
					<Checkbox id="rojo_usa" bind:checked={formData.semaforo_rojo_aduana_americana} />
					<Label for="rojo_usa" class="text-[10px]">{m['invoice_item_fa.continuation.red_usa']()}</Label>
				</div>
			</div>
		</div>

		{#if operationType === 1 || invoiceType === 'CR'}
			<!-- CFDI Section (Export Only) -->
			<div class="space-y-3 rounded border bg-muted/20 p-3">
				<h4 class="border-b pb-1 text-[10px] font-bold text-muted-foreground uppercase">
					{m['invoice_item_fa.continuation.cfdi_data_title']()}
				</h4>
				<div class="space-y-1">
					<Label for="cfdi_uuid" class="text-[10px]">{m['invoice_item_fa.continuation.cfdi_uuid_label']()}</Label>
					<Input id="cfdi_uuid" bind:value={formData.cfdi_uuid} class="h-6 text-[10px]" />
				</div>
				<div class="space-y-1">
					<Label for="path_pdf" class="text-[10px]">{m['invoice_item_fa.continuation.cfdi_pdf_label']()}</Label>
					<Input id="path_pdf" bind:value={formData.path_pdf} class="h-6 text-[10px]" />
				</div>
				<div class="space-y-1">
					<Label for="path_xml" class="text-[10px]">{m['invoice_item_fa.continuation.cfdi_xml_label']()}</Label>
					<Input id="path_xml" bind:value={formData.path_xml} class="h-6 text-[10px]" />
				</div>
			</div>
		{/if}
	</div>
</div>

<PortSelectorModal bind:open={showPortModal} onSelect={handlePortSelect} />
