<script lang="ts">
	import * as Card from '$lib/components/ui/card';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Button } from '$lib/components/ui/button';
	import { Checkbox } from '$lib/components/ui/checkbox';
	import * as RadioGroup from '$lib/components/ui/radio-group';
	import * as Select from '$lib/components/ui/select';
	import { Textarea } from '$lib/components/ui/textarea';
	import { Plus, Upload } from 'lucide-svelte';
	import type { Invoice } from '$lib/api/dashboard/a76/invoices';
	import { m } from '$lib/i18n/messages';

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

	if (!formData && invoice) {
		formData = {
			// Campo de comentario estatus
			comments_status: invoice.comments_status || '',
			// Campos que van en diferentes recursos pero se editan aquí
			transport_mode: invoice.logistics?.transport_mode || 'TRUCK',
			is_mixed: invoice.compliance_mx?.is_mixed || false,
			print_stamp: invoice.financials?.seal_value_2500 || false,
			rule_3121_parties_ii: invoice.compliance_mx?.rule_3121_parties_ii || false,
			// Errores (Copied from Continuation Tab)
			errores_facturacion: [],
			related_doc_id: invoice.related_doc_id || null,
			code_signature: invoice.compliance_mx?.signature_key || '',
			electronic_signature: invoice.compliance_mx?.electronic_signature || '',
			mandatory_person: invoice.compliance_mx?.acts_as || '',
			contingency_mode: invoice.compliance_mx?.contingency_mode || false,
			cove: invoice.compliance_mx?.edocument || '',
			operation_num: invoice.compliance_mx?.vucem_operation_num || '',
			adendas: invoice.compliance_mx?.addendum_vu || '',
			observations_vu: invoice.vu_observations || '',
			certified_number: invoice.compliance_mx?.certificate_number || '',
			entry_exit_date: invoice.logistics?.entry_exit_date || '',
			payment_date: invoice.logistics?.payment_date || '',
			// New Export fields
			bill_number: invoice.logistics?.bill_number || '',
			guide_number: invoice.logistics?.guide_number || '',
			shipment_number: invoice.logistics?.shipment_number || '',
			option_iv18: invoice.option_iv18 || '',
			delivered_status: invoice.logistics?.delivered_status || false,
			received_by: invoice.logistics?.received_by || '',
			delivery_date: invoice.logistics?.delivery_date
				? invoice.logistics.delivery_date.split('T')[0]
				: ''
		};
		exists = true;
	} else if (!formData) {
		formData = {
			// Campo de comentario estatus
			comments_status: '',
			// Campos que van en diferentes recursos pero se editan aquí
			transport_mode: 'TRUCK',
			is_mixed: false,
			print_stamp: false,
			rule_3121_parties_ii: false,
			// Errores
			errores_facturacion: [],
			related_doc_id: null,
			code_signature: '',
			electronic_signature: '',
			mandatory_person: '',
			contingency_mode: false,
			cove: '',
			operation_num: '',
			adendas: '',
			observations_vu: '',
			certified_number: '',
			entry_exit_date: '',
			payment_date: '',
			// New Export fields
			bill_number: '',
			guide_number: '',
			shipment_number: '',
			option_iv18: '',
			delivered_status: false,
			received_by: '',
			delivery_date: ''
		};
		exists = false;
	}

	$effect.pre(() => {
		if (formData) {
			if (formData.transport_mode === undefined) formData.transport_mode = 'TRUCK';
			if (formData.is_mixed === undefined) formData.is_mixed = false;
			if (formData.print_stamp === undefined) formData.print_stamp = false;
			if (formData.rule_3121_parties_ii === undefined) formData.rule_3121_parties_ii = false;
			if (formData.contingency_mode === undefined) formData.contingency_mode = false;
			if (formData.delivered_status === undefined) formData.delivered_status = false;
			if (formData.option_iv18 === undefined) formData.option_iv18 = '';
		}
	});

	// Campos que no están en el backend
	let rfc = $state('');
	let curp = $state('');

	function loadInfo() {
		// Función para cargar información
		console.log('Cargar información');
	}
</script>

{#if invoiceType !== 'MEX'}
	<div class="grid grid-cols-1 md:grid-cols-3 gap-3">
		<div class="space-y-3 rounded-md border p-3">
			<!-- Modo de Transporte -->
			<div class="space-y-2">
				<Label for="transport-mode">{m.invoice_edit_others_transport_mode_label()}</Label>
				<Select.Root
					type="single"
					value={formData.transport_mode}
					onValueChange={(value: string | undefined) =>
						(formData.transport_mode = value || 'TRUCK')}
				>
					<Select.Trigger id="transport-mode">
						{transportModes.find((m) => m.key === formData.transport_mode)?.name ||
							m.invoice_edit_others_select_mode_placeholder()}
					</Select.Trigger>
					<Select.Content>
						{#each transportModes as mode}
							<Select.Item value={mode.key}>
								{mode.name}
							</Select.Item>
						{/each}
					</Select.Content>
				</Select.Root>
			</div>

			{#if operationType !== 1 && invoiceType !== 'MEX'}
				<!-- Imprimir Sello -->
				<div class="space-y-2">
					<Label class="opacity-0">Spacer</Label>
					<div class="flex items-center space-x-2">
						<Checkbox id="print-stamp" bind:checked={formData.print_stamp} />
						<Label for="print-stamp" class="text-xs font-normal">
							{m.invoice_edit_others_print_stamp_label()}
						</Label>
					</div>
				</div>

				{#if invoiceType !== 'CR' && invoiceType !== 'REP' && invoiceType !== 'REPAR'}
					<!-- Es Mixto -->
					<div class="space-y-2">
						<Label class="opacity-0">Spacer</Label>
						<Label class="text-xs">{m.invoice_edit_others_mixed_label()}</Label>
						<RadioGroup.Root
							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 space-x-2">
								<RadioGroup.Item value="true" id="mixed-si" class="h-4 w-4" />
								<Label for="mixed-si" class="cursor-pointer text-xs font-normal">{m.invoice_edit_others_yes()}</Label>
							</div>
							<div class="flex items-center space-x-2">
								<RadioGroup.Item value="false" id="mixed-no" class="h-4 w-4" />
								<Label for="mixed-no" class="cursor-pointer text-xs font-normal">{m.invoice_edit_others_no()}</Label>
							</div>
						</RadioGroup.Root>
					</div>
				{/if}
			{/if}

			{#if (operationType === 1 || invoiceType === 'CR') && invoiceType !== 'REP' && invoiceType !== 'REPAR'}
				<!-- Export Fields (Hidden for Repair) -->
				<div class="space-y-2 pt-2">
					<Label for="bill_number">{m.invoice_edit_others_master_bol_label()}</Label>
					<Input id="bill_number" bind:value={formData.bill_number} class="h-8 text-xs" />
				</div>
				<div class="space-y-2">
					<Label for="guide_number">{m.invoice_edit_others_guide_number_label()}</Label>
					<Input id="guide_number" bind:value={formData.guide_number} class="h-8 text-xs" />
				</div>
				<div class="space-y-2">
					<Label for="shipment_number">{m.invoice_edit_others_shipment_number_label()}</Label>
					<Input id="shipment_number" bind:value={formData.shipment_number} class="h-8 text-xs" />
				</div>
				<div class="space-y-2 pb-2">
					<Label for="option_iv18">{m.invoice_edit_others_option_iv18_label()}</Label>
					<Select.Root
						type="single"
						value={formData.option_iv18}
						onValueChange={(v: string | undefined) => (formData.option_iv18 = v || '')}
					>
						<Select.Trigger id="option_iv18" class="h-8 text-xs">
							{formData.option_iv18 || m.invoice_edit_others_select_option_placeholder()}
						</Select.Trigger>
						<Select.Content>
							<Select.Item value="OPCION 1">Opción 1</Select.Item>
						</Select.Content>
					</Select.Root>
				</div>

				<!-- DATOS ENTREGA -->
				<div class="mt-4 space-y-3 rounded-md border bg-muted/20 p-3">
					<h4 class="mb-2 border-b pb-1 text-xs font-bold text-muted-foreground uppercase">
						{m.invoice_edit_others_delivery_title()}
					</h4>
					<div class="mb-2 flex items-center space-x-2">
						<Checkbox id="delivered_status" bind:checked={formData.delivered_status} />
						<Label for="delivered_status" class="text-xs font-semibold">{m.invoice_edit_others_delivered_label()}</Label>
					</div>
					<div class="space-y-2">
						<Label for="received_by" class="text-xs">{m.invoice_edit_others_received_by_label()}</Label>
						<Input
							id="received_by"
							bind:value={formData.received_by}
							disabled={!formData.delivered_status}
							class="h-7 text-xs"
						/>
					</div>
					<div class="space-y-2">
						<Label for="delivery_date" class="text-xs">{m.invoice_edit_others_delivery_date_label()}</Label>
						<Input
							id="delivery_date"
							type="date"
							bind:value={formData.delivery_date}
							disabled={!formData.delivered_status}
							class="h-7 text-xs"
						/>
					</div>
				</div>
			{/if}

			{#if operationType !== 1 && invoiceType !== 'CR' && invoiceType !== 'REP' && invoiceType !== 'REPAR'}
				<div class="flex items-center space-x-2 py-2">
					<Checkbox id="rule-3121" bind:checked={formData.rule_3121_parties_ii} />
					<Label for="rule-3121" class="text-xs font-normal">{m.invoice_edit_others_rule_3121_label()}</Label>
				</div>
			{/if}

			<!-- Comentario estatus -->
			<div class="space-y-2">
				<Label class="opacity-0">Spacer</Label>
				<Label>{m.invoice_edit_others_status_comment_label()}</Label>
				<Textarea
					id="comments_status"
					bind:value={formData.comments_status}
					placeholder={m.invoice_edit_others_status_comment_placeholder()}
					rows={3}
				/>
			</div>
		</div>

		<div class="col-span-1 md:col-span-2 space-y-3 rounded-md border p-3">
			<div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
				<!-- ID Relación Docs -->
				<div class="space-y-2">
					<Label for="relation-docs-id">{m.invoice_edit_others_related_docs_label()}</Label>
					<Input id="relation-docs-id" type="number" bind:value={formData.related_doc_id} />
				</div>

				<!-- Firma Electrónica -->
				<div class="space-y-2 md:col-span-2">
					<Label for="electronic-sig-1">{m.invoice_edit_others_electronic_signature_label()}</Label>
					<div class="flex gap-2">
						<Input id="electronic-sig-1" bind:value={formData.code_signature} class="flex-1" />
						<Button variant="outline" size="icon">
							<Upload class="h-4 w-4" />
						</Button>
					</div>
				</div>

				<!-- Mandatario/Persona Autorizada -->
				<div class="space-y-2">
					<Label for="mandatory-person">{m.invoice_edit_others_authorized_person_label()}</Label>
					<Input id="mandatory-person" bind:value={formData.mandatory_person} />
				</div>

				<!-- RFC -->
				<div class="space-y-2">
					<Label id="rfc" for="rfc">RFC: {rfc}</Label>
				</div>

				<!-- CURP -->
				<div class="space-y-2">
					<Label id="curp" for="curp">CURP: {curp}</Label>
				</div>

				<!-- Modo Contingencia -->
				<div class="col-span-4 space-y-2">
					<div class="flex items-center space-x-2">
						<Checkbox id="contingency-mode" bind:checked={formData.contingency_mode} />
						<Label for="contingency-mode" class="font-normal">{m.invoice_edit_others_contingency_mode_label()}</Label>
					</div>

					<!-- COVE -->
					<div class="space-y-2">
						<Label for="cove">{m.invoice_edit_others_cove_label()}</Label>
						<Input id="cove" bind:value={formData.cove} placeholder={m.invoice_edit_others_cove_label()} />
					</div>

					<!-- Número de Operación -->
					<div class="space-y-2">
						<Label for="operation-num">{m.invoice_edit_others_operation_number_label()}</Label>
						<Input id="operation-num" bind:value={formData.operation_num} />
					</div>
					<!-- Adenda(s) -->
					<div class="space-y-2 md:col-span-2">
						<Label for="adendas">{m.invoice_edit_others_adendas_label()}</Label>
						<Input id="adendas" bind:value={formData.adendas} />
					</div>

					<!-- Observaciones VU -->
					<div class="space-y-2 md:col-span-2">
						<Label for="observations-vu">{m.invoice_edit_others_vu_observations_label()}</Label>
						<div class="flex gap-2">
							<Textarea
								id="observations-vu"
								bind:value={formData.observations_vu}
								class="min-h-[60px] flex-1"
							/>
							<Button variant="outline" onclick={loadInfo}>{m.invoice_edit_others_load_info()}</Button>
						</div>
					</div>

					<!-- Fechas Logísticas (From HEAD) -->
					<div class="space-y-2">
						<Label for="entry_exit_date">{m.invoice_edit_others_entry_exit_date_label()}</Label>
						<Input id="entry_exit_date" type="date" bind:value={formData.entry_exit_date} />
					</div>
					<div class="space-y-2">
						<Label for="payment_date">{m.invoice_edit_others_payment_date_label()}</Label>
						<Input id="payment_date" type="date" bind:value={formData.payment_date} />
					</div>

					<!-- Número Certificado -->
					<div class="space-y-2">
						<Label for="certified-num">{m.invoice_edit_others_certificate_number_label()}</Label>
						<Input id="certified-num" bind:value={formData.certified_number} />
					</div>

					<!-- Firma Electrónica 2 -->
					<div class="space-y-2 md:col-span-2">
						<Label for="electronic-sig-2">{m.invoice_edit_others_electronic_signature_2_label()}</Label>
						<Input id="electronic-sig-2" bind:value={formData.electronic_signature} />
					</div>
				</div>
			</div>
		</div>
	</div>
{:else}
	<div class="space-y-4 rounded-md border p-4">
		<h4 class="text-xs font-semibold text-muted-foreground uppercase">{m.invoice_edit_others_errors_title()}</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_edit_others_line()}</th>
						<th class="border px-2 py-1 text-left">{m.invoice_edit_others_key()}</th>
						<th class="border px-2 py-1 text-left">{m.invoice_edit_others_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_edit_others_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_edit_others_insert()}</Button>
			<Button variant="outline" size="sm" class="h-7 text-xs">{m.invoice_edit_others_edit()}</Button>
			<Button variant="outline" size="sm" class="h-7 text-xs">{m.invoice_edit_others_delete()}</Button>
		</div>
	</div>
{/if}
