<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 { Switch } from '$lib/components/ui/switch';
	import type { Invoice } from '$lib/api/dashboard/a76/invoices';
	import type { InvoiceType } from '$lib/api/dashboard/reference_data/invoice_types';
	import type { Pedimento } from '$lib/api/dashboard/a76/pedimentos';

	let {
		invoice,
		formData = $bindable(),
		invoiceTypes = [],
		pedimentos = [],
		defaultOperationType = undefined,
		defaultInvoiceType = undefined,
		invoiceType = undefined
	}: {
		invoice: Invoice | null;
		formData?: any;
		invoiceTypes?: InvoiceType[];
		pedimentos?: Pedimento[];
		defaultOperationType?: string | null;
		defaultInvoiceType?: string | null;
		invoiceType?: string;
	} = $props();

	function handlePedimentoChange(pedimentoId: string) {
		if (!pedimentoId) return;

		const selectedPedimento = pedimentos.find((p) => p.id === parseInt(pedimentoId));
		if (!selectedPedimento) return;

		// Si el tipo de operación está vacío, llenarlo con el del pedimento
		if (selectedPedimento.operation_type && !formData.operation_type) {
			formData.operation_type = selectedPedimento.operation_type;
		}

		// Actualizar los campos del pedimento en formData
		formData.fecha_pedimento_del = selectedPedimento.pedimento_dates?.start_date || '';
		formData.fecha_pedimento_al = selectedPedimento.pedimento_dates?.end_date || '';
		formData.clave_pedimento = selectedPedimento.pedimento_code || '';
		formData.regimen_pedimento = selectedPedimento.regime || '';

		// Construir el número de pedimento completo
		const pedimentoNumber =
			`${selectedPedimento.customs_office?.slice(0, 2) || ''}-${selectedPedimento.license || ''}-${selectedPedimento.pedimento_number || ''}`.replace(
				/^-+|-+$/g,
				''
			);
		formData.pedimento = pedimentoNumber;
	}

	$effect(() => {
		if (formData?.pedimento_id && pedimentos.length > 0 && !formData.pedimento) {
			handlePedimentoChange(formData.pedimento_id);
		}
	});

	// Efecto para actualizar operation_type cuando cambia defaultOperationType
	$effect(() => {
		if (formData && defaultOperationType !== undefined && defaultOperationType !== null) {
			// Si operation_type está vacío, null, o undefined, actualizarlo con defaultOperationType
			if (!formData.operation_type) {
				formData.operation_type = defaultOperationType;
			}
		}
	});

	if (!formData) {
		let operationType: string | null = null;
		if (invoice?.operation_type) {
			operationType = invoice.operation_type;
		} else if (defaultOperationType !== undefined) {
			operationType = defaultOperationType ?? null;
		}

		formData = {
			is_pedimento_pending: false,
			pedimento_id: invoice?.compliance_mx?.pedimento_id || '',
			remesa: invoice?.compliance_mx?.remesa || '',

			invoice_number: invoice?.invoice_number || '',
			invoice_date: invoice?.invoice_date || new Date().toISOString().split('T')[0],
			emission_date: new Date().toISOString().split('T')[0],
			operation_type: operationType,
			invoice_type: invoice?.invoice_type || (defaultInvoiceType ?? ''),
			// Campos del pedimento (se llenarán al seleccionar un pedimento)
			fecha_pedimento_del: '',
			fecha_pedimento_al: '',
			clave_pedimento: '',
			regimen_pedimento: '',
			// Campos específicos para MEX
			iva_factor: invoice?.financials?.iva_factor || '',
			alternate_invoice: invoice?.alternate_invoice || ''
		};
	} else {
		// Si formData ya existe pero operation_type está vacío, usar defaultOperationType
		if (
			!formData.operation_type &&
			defaultOperationType !== undefined &&
			defaultOperationType !== null
		) {
			formData.operation_type = defaultOperationType;
		}
		// Ensure new fields exist if formData was created before
		if (formData.iva_factor === undefined)
			formData.iva_factor = invoice?.financials?.iva_factor || '';
		if (formData.alternate_invoice === undefined)
			formData.alternate_invoice = invoice?.alternate_invoice || '';
	}
	// Filter invoice types based on operation type
	let filteredInvoiceTypes = $derived(
		invoiceTypes.filter((type) => {
			if (!formData.operation_type) return true;
			return type.operation === 'both' || type.operation === formData.operation_type;
		})
	);

	// Reset invoice_type if not valid for new operation_type
	$effect(() => {
		if (formData.operation_type && formData.invoice_type) {
			const isValid = filteredInvoiceTypes.some((t) => t.key === formData.invoice_type);
			if (!isValid) {
				formData.invoice_type = '';
			}
		}
	});

	// Limpiar pedimento seleccionado si ya no está en la lista filtrada (p. ej. al cambiar tipo de factura)
	$effect(() => {
		const pid = formData?.pedimento_id;
		const list = pedimentos || [];
		if (pid == null || pid === '') return;
		const id = typeof pid === 'string' ? parseInt(pid, 10) : pid;
		if (Number.isNaN(id)) return;
		const found = list.some((p) => p.id === id);
		if (!found) {
			formData.pedimento_id = null;
			formData.pedimento = '';
			formData.fecha_pedimento_del = '';
			formData.fecha_pedimento_al = '';
			formData.clave_pedimento = '';
			formData.regimen_pedimento = '';
		}
	});
</script>

<!-- Datos Principales en una fila compacta (reusable across tabs) -->
<div class="flex flex-wrap items-end gap-3 pb-3">
	<div class="min-w-[100px] flex-1 space-y-1">
		<Label for="operation_type" class="text-xs"
			>Tipo de Operación<span class="text-red-500">*</span></Label
		>
		<Select.Root
			type="single"
			value={formData.operation_type || ''}
			onValueChange={(v) => {
				formData.operation_type = v;
			}}
		>
			<Select.Trigger id="operation_type" class="h-8 text-sm">
				<span class="truncate">
					{formData.operation_type ? (formData.operation_type === 'exp' ? 'Exp' : 'Imp') : '...'}
				</span>
			</Select.Trigger>
			<Select.Content>
				<Select.Item value="exp">Exportación</Select.Item>
				<Select.Item value="imp">Importación</Select.Item>
			</Select.Content>
		</Select.Root>
	</div>
	<div class="min-w-[100px] flex-1 space-y-1">
		<Label for="operation_type" class="text-xs"
			>Tipo de factura <span class="text-red-500">*</span></Label
		>
		<Select.Root
			type="single"
			value={formData.invoice_type || ''}
			onValueChange={(v) => {
				formData.invoice_type = v ?? '';
			}}
		>
			<Select.Trigger id="invoice_type" class="h-7 text-xs">
				<span class="truncate">
					{formData.invoice_type ? `${formData.invoice_type}` : '...'}
				</span>
			</Select.Trigger>
			<Select.Content class="max-h-[300px]">
				{#each filteredInvoiceTypes as type}
					<Select.Item value={type.key}>
						{type.key} - {type.description}
					</Select.Item>
				{/each}
			</Select.Content>
		</Select.Root>
	</div>

	{#if invoiceType !== 'MEX'}
		<div class="flex flex-col items-center space-y-1 pb-1">
			<Label for="is_pedimento_pending" class="text-xs">Pedimento Pendiente?</Label>
			<Switch
				id="is_pedimento_pending"
				checked={formData.is_pedimento_pending}
				onCheckedChange={(checked) => {
					formData.is_pedimento_pending = checked;
					if (checked) {
						formData.pedimento_id = null;
						formData.pedimento = '';
						formData.remesa = '';
						formData.fecha_pedimento_del = '';
						formData.fecha_pedimento_al = '';
						formData.clave_pedimento = '';
						formData.regimen_pedimento = '';
					}
				}}
			/>
		</div>
		<div class="min-w-[75px] flex-[2] space-y-1">
			<Label for="pedimento" class="text-xs">Pedimento</Label>
		<Select.Root
				type="single"
				value={formData.pedimento_id ? String(formData.pedimento_id) : ''}
				disabled={formData.is_pedimento_pending}
				onValueChange={(v) => {
					formData.pedimento_id = v ? parseInt(v) : null;
					if (v) {
						handlePedimentoChange(v);
					}
				}}
			>
				<Select.Trigger id="pedimento" class="h-8 text-sm">
					<span class="truncate">
						{formData.pedimento || 'Selecciona pedimento...'}
					</span>
				</Select.Trigger>
				<Select.Content class="max-h-[300px]">
					{#each pedimentos as pedimento}
						<Select.Item value={String(pedimento.id)}>
							{pedimento.customs_office?.slice(
								0,
								2
							)}-{pedimento.license}-{pedimento.pedimento_number}
						</Select.Item>
					{/each}
				</Select.Content>
			</Select.Root>
		</div>

		<div class="min-w-[80px] flex-1 space-y-1">
			<Label for="remesa" class="text-xs">Remesa</Label>
			<Input id="remesa" bind:value={formData.remesa} class="h-8 text-sm" />
		</div>
	{/if}

	<div class="min-w-[140px] flex-[2] space-y-1">
		<Label for="invoice_number" class="text-xs"
			>Núm. Factura <span class="text-red-500">*</span></Label
		>
		<Input
			id="invoice_number"
			bind:value={formData.invoice_number}
			class="h-8 text-sm font-medium"
			required
		/>
	</div>

	<div class="min-w-[140px] flex-[2] space-y-1">
		<Label for="invoice_date" class="text-xs">
			{formData.operation_type === 'exp' || invoiceType === 'CR'
				? 'Fecha'
				: invoiceType === 'MEX'
					? 'Fecha de Entrada'
					: 'Fecha Factura'}
			<span class="text-red-500">*</span>
		</Label>
		<Input id="invoice_date" type="date" bind:value={formData.invoice_date} class="h-8 text-sm" />
	</div>

	<div class="min-w-[140px] flex-[2] space-y-1">
		<Label for="emission_date" class="text-xs">Fecha Emisión</Label>
		<Input id="emission_date" type="date" bind:value={formData.emission_date} class="h-8 text-sm" />
	</div>

	{#if invoiceType === 'MEX'}
		<div class="min-w-[90px] flex-1 space-y-1">
			<Label for="iva_factor" class="text-xs">Factor IVA</Label>
			<Input id="iva_factor" bind:value={formData.iva_factor} class="h-8 text-sm" />
		</div>
		<div class="min-w-[140px] flex-[2] space-y-1">
			<Label for="alternate_invoice" class="text-xs">Factura Alterna</Label>
			<Input id="alternate_invoice" bind:value={formData.alternate_invoice} class="h-8 text-sm" />
		</div>
	{/if}
</div>
