<script lang="ts">
	import * as Select from '$lib/components/ui/select';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Textarea } from '$lib/components/ui/textarea/index.js';
	import type { Invoice } from '$lib/api/dashboard/a76/invoices';

	let {
		invoice,
		formData = $bindable(),
		exists = $bindable(),
		seals = [],
		incoterms = [],
		valuationMethods = [],
		legends = [],
		enclosure = [],
		operationType = undefined,
		invoiceType = undefined
	}: {
		invoice: Invoice | null;
		formData?: any;
		exists?: boolean;
		seals?: any[];
		incoterms?: any[];
		valuationMethods?: any[];
		legends?: any[];
		enclosure?: any[];
		operationType?: number;
		invoiceType?: string;
	} = $props();

	let selectedLegendCode = $state<string>('');

	function appendLegendToEs() {
		const code = selectedLegendCode;
		if (!code) return;
		const legend = legends.find((l) => String(l.code) === String(code));
		const text = legend?.description?.trim();
		if (!text) return;
		const current = (formData.observation_es || '').trim();
		formData.observation_es = current ? `${current}\n${text}` : text;
	}

	if (!formData && invoice) {
		formData = {
			// Campos de observaciones
			observation_es: invoice.observation_es || '',
			observation_en: invoice.observation_en || '',
			// Incrementables
			freight: invoice.financials?.freight || null,
			insurance_value: invoice.financials?.insurance_value || null,
			insurance: invoice.financials?.insurance || null,
			packaging: invoice.financials?.packaging || null,
			other_increments: invoice.financials?.other_increments || null,
			total_increments_mn: invoice.financials?.total_increments_mn || null,
			total_increments_me: invoice.financials?.total_increments_me || null,
			// Incoterm y recinto
			incoterm: invoice.logistics?.incoterm || '',
			enclosure: invoice.compliance_mx?.enclosure || null,
			// Campos de esta pestaña
			num_seals: null,
			movement_type: invoice.compliance_mx?.movement_type || '',
			alternate_invoice: invoice.alternate_invoice || '',
			valuation_method: invoice.compliance_mx?.value_method || '',
			// New fields for Export
			other_deductibles: invoice.financials?.other_deductibles || null,
			proforma_number: invoice.proforma_number || '',
			sub_division: invoice.compliance_mx?.subdivision || '',
			acts_as_cd: invoice.logistics?.acts_as_cd || false,
			identifier_1: invoice.logistics?.identifier_1 || '',
			complement_1: invoice.logistics?.complement_1 || '',
			identifier_2: invoice.logistics?.identifier_2 || '',
			complement_2: invoice.logistics?.complement_2 || '',
			office_document: invoice.compliance_mx?.office_document || '',
			is_mixed: invoice.compliance_mx?.is_mixed || false
		};
		exists = true;
	} else if (!formData) {
		formData = {
			// Campos de observaciones
			observation_es: '',
			observation_en: '',
			// Incrementables
			freight: null,
			insurance_value: null,
			insurance: null,
			packaging: null,
			other_increments: null,
			total_increments_mn: null,
			total_increments_me: null,
			// Incoterm y recinto
			incoterm: '',
			enclosure: null,
			// Campos de esta pestaña
			num_seals: null,
			movement_type: '',
			alternate_invoice: '',
			valuation_method: '',
			// New fields for Export
			other_deductibles: null,
			proforma_number: '',
			sub_division: '',
			acts_as_cd: false,
			identifier_1: '',
			complement_1: '',
			identifier_2: '',
			complement_2: '',
			office_document: '',
			is_mixed: false
		};
		exists = false;
	}
</script>

<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
	<!-- Left Column: Observations and Catalog Info -->
	<div class="space-y-4">
		<!-- Observations Section -->
		<div class="space-y-4 rounded-md border p-3">
			<div class="space-y-2">
				<h4 class="text-xs font-semibold text-muted-foreground uppercase">
					{operationType === 1 || invoiceType === 'CR'
						? 'Observaciones de la factura mexicana:'
						: invoiceType === 'MEX'
							? 'Observacion de la factura mexicana y bilingue:'
							: 'Observacion de la factura mexicana y bilingue:'}
				</h4>
				<Textarea
					id="observation_es"
					bind:value={formData.observation_es}
					class="max-h-[150px] min-h-[150px] text-sm font-medium"
					placeholder="Escribe tus observaciones aqui."
				/>
			</div>

			{#if legends?.length}
				<div class="grid grid-cols-1 sm:grid-cols-[1fr_auto] gap-2">
					<div class="space-y-1">
						<Label for="legend_code" class="text-xs">Leyenda fija:</Label>
						<Select.Root
							type="single"
							value={selectedLegendCode}
							onValueChange={(v) => {
								selectedLegendCode = v ?? '';
							}}
						>
							<Select.Trigger id="legend_code" class="h-7 text-xs">
								<span class="truncate">
									{selectedLegendCode ? `Clave ${selectedLegendCode}` : 'Selecciona leyenda...'}
								</span>
							</Select.Trigger>
							<Select.Content class="max-h-[300px]">
								{#each legends as l}
									<Select.Item value={String(l.code)}>
										{l.code} - {l.description || ''}
									</Select.Item>
								{/each}
							</Select.Content>
						</Select.Root>
					</div>
					<div class="flex items-end">
						<button
							type="button"
							class="h-7 px-3 rounded-md border text-xs hover:bg-muted"
							onclick={appendLegendToEs}
						>
							Agregar a observaciones
						</button>
					</div>
				</div>
			{/if}

			{#if invoiceType !== 'MEX'}
				<div class="space-y-2">
					<h4 class="text-xs font-semibold text-muted-foreground uppercase">
						Observaciones de la factura americana:
					</h4>
					<Textarea
						id="observation_en"
						bind:value={formData.observation_en}
						class="max-h-[150px] min-h-[150px] text-sm font-medium"
						placeholder="Escribe tus observaciones aqui."
					/>
				</div>
			{/if}
		</div>

		{#if operationType === 1 || invoiceType === 'CR'}
			<!-- Identificadores (Export Only) -->
			<div class="space-y-4 rounded-md border bg-muted/20 p-4">
				<h4 class="mb-1 border-b pb-2 text-xs font-bold text-muted-foreground uppercase">
					Identificadores
				</h4>
				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-1.5">
						<Label for="identifier_1" class="text-xs font-semibold">Primero:</Label>
						<Input
							id="identifier_1"
							bind:value={formData.identifier_1}
							class="h-8 text-xs"
							placeholder="Clave..."
						/>
					</div>
					<div class="space-y-1.5">
						<Label for="identifier_2" class="text-xs font-semibold">Segundo:</Label>
						<Input
							id="identifier_2"
							bind:value={formData.identifier_2}
							class="h-8 text-xs"
							placeholder="Clave..."
						/>
					</div>
				</div>
			</div>

			<!-- Complementos (Export Only) -->
			<div class="space-y-4 rounded-md border bg-muted/20 p-4">
				<h4 class="mb-1 border-b pb-2 text-xs font-bold text-muted-foreground uppercase">
					Complementos
				</h4>
				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-1.5">
						<Label for="complement_1" class="text-xs font-semibold">1:</Label>
						<Input id="complement_1" bind:value={formData.complement_1} class="h-8 text-xs" />
					</div>
					<div class="space-y-1.5">
						<Label for="complement_2" class="text-xs font-semibold">2:</Label>
						<Input id="complement_2" bind:value={formData.complement_2} class="h-8 text-xs" />
					</div>
				</div>
			</div>

			<!-- Oficio (Export Only) -->
			<div class="rounded-md border bg-muted/20 p-3">
				<div class="space-y-1.5">
					<Label for="office_document" class="text-xs font-semibold">Oficio:</Label>
					<Input id="office_document" bind:value={formData.office_document} class="h-8 text-xs" />
				</div>
			</div>
		{/if}
	</div>

	<!-- Right Column: Values, Flags and Logistics -->
	<div class="space-y-4">
		<!-- Incrementables Section -->
		<div class="space-y-3 rounded-md border p-3">
			<h4 class="text-xs font-semibold text-muted-foreground uppercase">Incrementables:</h4>
			<div class="grid grid-cols-2 gap-x-4 gap-y-2">
				<div class="flex items-center">
					<Label for="freight" class="text-xs">Flete:</Label>
				</div>
				<Input
					id="freight"
					type="number"
					bind:value={formData.freight}
					class="h-8 text-sm font-medium"
				/>

				<div class="flex items-center">
					<Label for="insurance" class="text-xs">Seguros:</Label>
				</div>
				<Input
					id="insurance"
					type="number"
					bind:value={formData.insurance}
					class="h-8 text-sm font-medium"
				/>

				<div class="flex items-center">
					<Label for="packaging" class="text-xs">Embalajes:</Label>
				</div>
				<Input
					id="packaging"
					type="number"
					bind:value={formData.packaging}
					class="h-8 text-sm font-medium"
				/>

				<div class="flex items-center">
					<Label for="other_increments" class="text-xs leading-none">Otros increm.:</Label>
				</div>
				<Input
					id="other_increments"
					type="number"
					bind:value={formData.other_increments}
					class="h-8 text-sm font-medium"
				/>

				{#if operationType === 1 || invoiceType === 'CR'}
					<div class="flex items-center">
						<Label for="other_deductibles" class="text-xs leading-none">Otros deduc.:</Label>
					</div>
					<Input
						id="other_deductibles"
						type="number"
						bind:value={formData.other_deductibles}
						class="h-8 border-orange-200 text-sm font-medium focus-visible:ring-orange-200"
					/>
				{/if}
			</div>
		</div>

		{#if operationType === 1 || invoiceType === 'CR'}
			<!-- Precintos & Tipo Mov Group (No Title) -->
			<div class="grid grid-cols-1 sm:grid-cols-2 gap-4 rounded-md border bg-muted/20 p-3">
				<div class="space-y-1">
					<Label for="num_seals_exp" class="text-xs font-semibold">Número de Precinto:</Label>
					<Select.Root
						type="single"
						value={formData.num_seals ? String(formData.num_seals) : ''}
						onValueChange={(v) => {
							formData.num_seals = v ? parseInt(v) : null;
						}}
					>
						<Select.Trigger id="num_seals_exp" class="h-8 text-xs">
							<span class="truncate">
								{formData.num_seals
									? seals.find((p) => p.id === formData.num_seals)?.name || 'Selecciona...'
									: 'Selecciona...'}
							</span>
						</Select.Trigger>
						<Select.Content class="max-h-[300px]">
							{#each seals as seal}
								<Select.Item value={String(seal.id)}>
									{seal.name}
								</Select.Item>
							{/each}
						</Select.Content>
					</Select.Root>
				</div>
				<div class="space-y-1">
					<Label for="movement_type_exp" class="text-xs font-semibold">Tipo Movimiento:</Label>
					<Input
						id="movement_type_exp"
						bind:value={formData.movement_type}
						class="h-8 text-xs font-medium"
					/>
				</div>
			</div>

			<!-- Factura Alterna & Flags Section -->
			<div class="space-y-4 rounded-md border bg-muted/20 p-4">
				<h4 class="mb-1 border-b pb-2 text-xs font-bold text-muted-foreground uppercase">
					Factura Alterna & Flags
				</h4>
				<div class="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4">
					<div class="space-y-1.5">
						<Label for="alternate_invoice_exp" class="text-xs font-semibold">Factura Alterna:</Label
						>
						<Input
							id="alternate_invoice_exp"
							bind:value={formData.alternate_invoice}
							class="h-8 text-xs"
						/>
					</div>
					<div class="space-y-1.5">
						<Label for="proforma_number" class="text-xs font-semibold">Número de Proforma:</Label>
						<Input id="proforma_number" bind:value={formData.proforma_number} class="h-8 text-xs" />
					</div>

					<div class="space-y-2 pt-1">
						<Label class="mb-2 block text-xs font-semibold">Sub División:</Label>
						<div class="flex items-center gap-4">
							<label class="group flex cursor-pointer items-center gap-2">
								<div
									class="relative flex h-4 w-4 items-center justify-center rounded-full border-2 border-zinc-400 transition-all {formData.sub_division ===
									'si'
										? 'border-zinc-800 bg-zinc-800'
										: ''}"
								>
									<input
										type="radio"
										value="si"
										bind:group={formData.sub_division}
										class="sr-only"
									/>
									{#if formData.sub_division === 'si'}<div
											class="h-1.5 w-1.5 rounded-full bg-white"
										></div>{/if}
								</div>
								<span class="text-xs font-medium transition-colors group-hover:text-zinc-800"
									>Si</span
								>
							</label>
							<label class="group flex cursor-pointer items-center gap-2">
								<div
									class="relative flex h-4 w-4 items-center justify-center rounded-full border-2 border-zinc-400 transition-all {formData.sub_division ===
									'no'
										? 'border-zinc-800 bg-zinc-800'
										: ''}"
								>
									<input
										type="radio"
										value="no"
										bind:group={formData.sub_division}
										class="sr-only"
									/>
									{#if formData.sub_division === 'no'}<div
											class="h-1.5 w-1.5 rounded-full bg-white"
										></div>{/if}
								</div>
								<span class="text-xs font-medium transition-colors group-hover:text-zinc-800"
									>No</span
								>
							</label>
						</div>
					</div>

					<div class="space-y-2 pt-1">
						<Label class="mb-2 block text-xs font-semibold">Funge como CD:</Label>
						<div class="flex items-center gap-4">
							<label class="group flex cursor-pointer items-center gap-2">
								<div
									class="relative flex h-4 w-4 items-center justify-center rounded-full border-2 border-zinc-400 transition-all {formData.acts_as_cd ===
									true
										? 'border-zinc-800 bg-zinc-800'
										: ''}"
								>
									<input
										type="radio"
										value={true}
										bind:group={formData.acts_as_cd}
										class="sr-only"
									/>
									{#if formData.acts_as_cd === true}
										<div class="h-1.5 w-1.5 rounded-full bg-white"></div>{/if}
								</div>
								<span class="text-xs font-medium transition-colors group-hover:text-zinc-800"
									>Si</span
								>
							</label>
							<label class="group flex cursor-pointer items-center gap-2">
								<div
									class="relative flex h-4 w-4 items-center justify-center rounded-full border-2 border-zinc-400 transition-all {formData.acts_as_cd ===
									false
										? 'border-zinc-800 bg-zinc-800'
										: ''}"
								>
									<input
										type="radio"
										value={false}
										bind:group={formData.acts_as_cd}
										class="sr-only"
									/>
									{#if formData.acts_as_cd === false}
										<div class="h-1.5 w-1.5 rounded-full bg-white"></div>{/if}
								</div>
								<span class="text-xs font-medium transition-colors group-hover:text-zinc-800"
									>No</span
								>
							</label>
						</div>
					</div>
				</div>
			</div>
		{/if}

		<!-- Incoterm & Recinto (Show for all, layout adjusted) -->
		{#if invoiceType !== 'MEX'}
			<div class="space-y-3 rounded-md border p-3">
				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-1">
						<Label for="incoterm" class="text-xs">Incoterm:</Label>
						<Select.Root
							type="single"
							value={formData.incoterm || ''}
							onValueChange={(v) => {
								formData.incoterm = v ?? '';
							}}
						>
							<Select.Trigger id="incoterm" class="h-7 text-xs">
								<span class="truncate"
									>{formData.incoterm || 'Selecciona...'}</span
								>
							</Select.Trigger>
							<Select.Content class="max-h-[300px]">
								{#each incoterms as inco}
									<Select.Item value={String(inco.code)}>
										{inco.code} - {inco.description_es}
									</Select.Item>
								{/each}
							</Select.Content>
						</Select.Root>
					</div>
					<div class="space-y-1">
						<Label for="enclosure" class="text-xs">Recinto:</Label>
						<Select.Root
							type="single"
							value={formData.enclosure ? String(formData.enclosure) : ''}
							onValueChange={(v) => {
								formData.enclosure = v ? parseInt(v) : null;
							}}
						>
							<Select.Trigger id="enclosure" class="h-7 text-xs">
								<span class="truncate"
									>{formData.enclosure
										? enclosure.find((p) => p.id === formData.enclosure)?.name || 'Selecciona...'
										: 'Selecciona...'}</span
								>
							</Select.Trigger>
							<Select.Content class="max-h-[300px]">
								{#each enclosure as rec}
									<Select.Item value={String(rec.id)}>{rec.name}</Select.Item>
								{/each}
							</Select.Content>
						</Select.Root>
					</div>
				</div>
				{#if operationType === 1 || invoiceType === 'CR'}
					<div class="space-y-1 pt-1">
						<Label for="valuation_method_exp" class="text-xs font-semibold"
							>Método de Valoración:</Label
						>
						<Select.Root
							type="single"
							value={formData.valuation_method || ''}
							onValueChange={(v) => {
								formData.valuation_method = v ?? '';
							}}
						>
							<Select.Trigger id="valuation_method_exp" class="h-8 text-xs">
								<span class="truncate">{formData.valuation_method || 'Selecciona...'}</span>
							</Select.Trigger>
							<Select.Content>
								{#each valuationMethods as m}
									<Select.Item value={String(m.key)}>{m.key} - {m.description}</Select.Item>
								{/each}
							</Select.Content>
						</Select.Root>
					</div>
				{/if}
			</div>
		{/if}

		{#if invoiceType === 'MEX'}
			<div class="rounded-md border p-3">
				<div class="space-y-2">
					<Label class="mb-2 block text-xs font-semibold">Es mixto?</Label>
					<div class="flex items-center gap-4">
						<label class="group flex cursor-pointer items-center gap-2">
							<div
								class="relative flex h-4 w-4 items-center justify-center rounded-full border-2 border-zinc-400 transition-all {formData.is_mixed ===
								true
									? 'border-zinc-800 bg-zinc-800'
									: ''}"
							>
								<input type="radio" value={true} bind:group={formData.is_mixed} class="sr-only" />
								{#if formData.is_mixed === true}
									<div class="h-1.5 w-1.5 rounded-full bg-white"></div>{/if}
							</div>
							<span class="text-xs font-medium transition-colors group-hover:text-zinc-800">Si</span
							>
						</label>
						<label class="group flex cursor-pointer items-center gap-2">
							<div
								class="relative flex h-4 w-4 items-center justify-center rounded-full border-2 border-zinc-400 transition-all {formData.is_mixed ===
								false
									? 'border-zinc-800 bg-zinc-800'
									: ''}"
							>
								<input type="radio" value={false} bind:group={formData.is_mixed} class="sr-only" />
								{#if formData.is_mixed === false}
									<div class="h-1.5 w-1.5 rounded-full bg-white"></div>{/if}
							</div>
							<span class="text-xs font-medium transition-colors group-hover:text-zinc-800">No</span
							>
						</label>
					</div>
				</div>
			</div>
		{/if}
	</div>

	<!-- Extra Bottom Row for Import Mode specific fields (Original Layout preserved for Import) -->
	{#if operationType !== 1 && invoiceType !== 'MEX' && invoiceType !== 'CR'}
	<div class="col-span-1 md:col-span-2 space-y-3 rounded-md border p-3">
		<div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
				<div class="space-y-1">
					<Label for="num_seals" class="text-xs">Num Precintos:</Label>
					<Select.Root
						type="single"
						value={formData.num_seals ? String(formData.num_seals) : ''}
						onValueChange={(v) => {
							formData.num_seals = v ? parseInt(v) : null;
						}}
					>
						<Select.Trigger id="num_seals" class="h-7 text-xs">
							<span class="truncate"
								>{formData.num_seals
									? seals.find((p) => p.id === formData.num_seals)?.name || 'Selecciona...'
									: 'Selecciona...'}</span
							>
						</Select.Trigger>
						<Select.Content class="max-h-[300px]">
							{#each seals as seal}<Select.Item value={String(seal.id)}>{seal.name}</Select.Item
								>{/each}
						</Select.Content>
					</Select.Root>
				</div>
				<div class="space-y-1">
					<Label for="movement_type" class="text-xs">Tipo Movimiento:</Label>
					<Input
						id="movement_type"
						bind:value={formData.movement_type}
						class="h-8 text-sm font-medium"
					/>
				</div>
				<div class="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 font-medium"
					/>
				</div>
				<div class="space-y-1">
					<Label for="valuation_method" class="text-xs">Met. Valoracion:</Label>
					<Select.Root
						type="single"
						value={formData.valuation_method || ''}
						onValueChange={(v) => {
							formData.valuation_method = v ?? '';
						}}
					>
						<Select.Trigger id="valuation_method" class="h-7 text-xs">
							<span class="truncate">{formData.valuation_method || 'Selecciona...'}</span>
						</Select.Trigger>
						<Select.Content class="max-h-[300px]">
							{#each valuationMethods as m}
								<Select.Item value={String(m.key)}>{m.key} - {m.description}</Select.Item>
							{/each}
						</Select.Content>
					</Select.Root>
				</div>
			</div>
		</div>
	{/if}
</div>
