<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Textarea } from '$lib/components/ui/textarea';
	import { Switch } from '$lib/components/ui/switch';
	import * as Tabs from '$lib/components/ui/tabs';
	import { companyStore } from '$lib/stores/company.svelte';
	import { createDoda, updateDoda, type Doda } from '$lib/api/dashboard/a76/general_catalogs/doda';

	import { obtenerAtajosFormularioDoda } from '$lib/config/shortcuts/dashboard/general_catalogs/doda/edit';

	let {
		open = $bindable(false),
		item = null,
		onSuccess
	}: {
		open: boolean;
		item?: Doda | null;
		onSuccess?: () => void;
	} = $props();

	const isEdit = $derived(!!item);
	const title = $derived(isEdit ? `Editar DODA ${item?.integration_number || ''}` : 'Nuevo DODA');

	// Estado del formulario
	let activeTab = $state('general');
	let formData = $state({
		integration_number: '',
		doda_date: undefined as number | undefined,
		doda_time: undefined as number | undefined,
		dispatch_customs: '',
		customs_sections: '',
		patent: '',
		pedimentos: '',
		caat: '',
		transport_identification: '',
		fast_id: '',
		operation_type: '',
		selected: false,
		user_selected: '',
		last_user: '',
		responsible: '',
		carrier: '',
		shipments: '',
		pedimento_type: '',
		original_chain: '',
		serial_number: '',
		electronic_signature: '',
		transaction_number: '',
		status: '',
		linq_sat_qr: '',
		sat_certificate: '',
		sat_digital_seal: '',
		xml_doda_sent_path: '',
		xml_doda_response_path: '',
		sat_original_chain: '',
		customs_clearance: undefined as number | undefined,
		unique_badge_number: ''
	});

	let loading = $state(false);
	let error = $state<string | null>(null);

	// Atajos

	// Cargar datos
	$effect(() => {
		if (open) {
			activeTab = 'general';
			if (item) {
				formData = {
					integration_number: item.integration_number || '',
					doda_date: item.doda_date,
					doda_time: item.doda_time,
					dispatch_customs: item.dispatch_customs || '',
					customs_sections: item.customs_sections || '',
					patent: item.patent || '',
					pedimentos: item.pedimentos || '',
					caat: item.caat || '',
					transport_identification: item.transport_identification || '',
					fast_id: item.fast_id || '',
					operation_type: item.operation_type || '',
					selected: item.selected || false,
					user_selected: item.user_selected || '',
					last_user: item.last_user || '',
					responsible: item.responsible || '',
					carrier: item.carrier || '',
					shipments: item.shipments || '',
					pedimento_type: item.pedimento_type || '',
					original_chain: item.original_chain || '',
					serial_number: item.serial_number || '',
					electronic_signature: item.electronic_signature || '',
					transaction_number: item.transaction_number || '',
					status: item.status || '',
					linq_sat_qr: item.linq_sat_qr || '',
					sat_certificate: item.sat_certificate || '',
					sat_digital_seal: item.sat_digital_seal || '',
					xml_doda_sent_path: item.xml_doda_sent_path || '',
					xml_doda_response_path: item.xml_doda_response_path || '',
					sat_original_chain: item.sat_original_chain || '',
					customs_clearance: item.customs_clearance,
					unique_badge_number: item.unique_badge_number || ''
				};
			} else {
				// Reset
				formData = {
					integration_number: '',
					doda_date: undefined,
					doda_time: undefined,
					dispatch_customs: '',
					customs_sections: '',
					patent: '',
					pedimentos: '',
					caat: '',
					transport_identification: '',
					fast_id: '',
					operation_type: '',
					selected: false,
					user_selected: '',
					last_user: '',
					responsible: '',
					carrier: '',
					shipments: '',
					pedimento_type: '',
					original_chain: '',
					serial_number: '',
					electronic_signature: '',
					transaction_number: '',
					status: '',
					linq_sat_qr: '',
					sat_certificate: '',
					sat_digital_seal: '',
					xml_doda_sent_path: '',
					xml_doda_response_path: '',
					sat_original_chain: '',
					customs_clearance: undefined,
					unique_badge_number: ''
				};
			}
			error = null;
		}
	});

	async function handleSubmit() {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) {
			error = 'No hay compañía seleccionada';
			return;
		}

		loading = true;
		error = null;

		try {
			const idToUpdate = item?.id;

			if (isEdit && idToUpdate) {
				await updateDoda(idToUpdate, formData, companyId);
			} else {
				await createDoda(formData, companyId);
			}

			open = false;
			if (onSuccess) onSuccess();
		} catch (e) {
			console.error(e);
			error = e instanceof Error ? e.message : 'Error al guardar DODA';
		} finally {
			loading = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[900px] max-h-[90vh] overflow-y-auto">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
		</Dialog.Header>

		<form
			onsubmit={(e) => {
				e.preventDefault();
				handleSubmit();
			}}
			class="py-4"
		>
			{#if error}
				<div class="mb-4 rounded-md bg-destructive/15 p-3 text-sm text-destructive">
					{error}
				</div>
			{/if}

			<Tabs.Root bind:value={activeTab} class="w-full">
				<Tabs.List class="grid w-full grid-cols-4">
					<Tabs.Trigger value="general">General</Tabs.Trigger>
					<Tabs.Trigger value="transport">Aduana/Transp.</Tabs.Trigger>
					<Tabs.Trigger value="sat">SAT / Digital</Tabs.Trigger>
					<Tabs.Trigger value="other">Otros</Tabs.Trigger>
				</Tabs.List>

				<!-- TAB: GENERAL -->
				<Tabs.Content value="general" class="space-y-4 py-4">
					<div class="grid grid-cols-2 gap-4">
						<div class="grid gap-2">
							<Label for="integration_number">No. Integración</Label>
							<Input
								id="integration_number"
								bind:value={formData.integration_number}
								maxlength={30}
							/>
						</div>
						<div class="grid gap-2">
							<Label for="status">Estatus</Label>
							<Input id="status" bind:value={formData.status} maxlength={30} />
						</div>
					</div>
					<div class="grid grid-cols-3 gap-4">
						<div class="grid gap-2">
							<Label for="doda_date">Fecha (YYYYMMDD)</Label>
							<Input type="number" id="doda_date" bind:value={formData.doda_date} />
						</div>
						<div class="grid gap-2">
							<Label for="doda_time">Hora (HHMMSS)</Label>
							<Input type="number" id="doda_time" bind:value={formData.doda_time} />
						</div>
						<div class="grid gap-2">
							<Label for="operation_type">Tipo Operación</Label>
							<Input id="operation_type" bind:value={formData.operation_type} maxlength={1} />
						</div>
					</div>
					<div class="grid gap-2">
						<Label for="pedimentos">Pedimentos</Label>
						<Input id="pedimentos" bind:value={formData.pedimentos} maxlength={80} />
					</div>
					<div class="grid gap-2">
						<Label for="pedimento_type">Tipo Pedimento</Label>
						<Input id="pedimento_type" bind:value={formData.pedimento_type} maxlength={30} />
					</div>
				</Tabs.Content>

				<!-- TAB: ADUANA / TRANSPORTE -->
				<Tabs.Content value="transport" class="space-y-4 py-4">
					<div class="grid grid-cols-3 gap-4">
						<div class="grid gap-2">
							<Label for="patent">Patente</Label>
							<Input id="patent" bind:value={formData.patent} maxlength={4} />
						</div>
						<div class="grid gap-2">
							<Label for="dispatch_customs">Aduana Despacho</Label>
							<Input id="dispatch_customs" bind:value={formData.dispatch_customs} maxlength={3} />
						</div>
						<div class="grid gap-2">
							<Label for="customs_sections">Sección Aduanera</Label>
							<Input id="customs_sections" bind:value={formData.customs_sections} maxlength={3} />
						</div>
					</div>
					<div class="grid grid-cols-2 gap-4">
						<div class="grid gap-2">
							<Label for="caat">CAAT</Label>
							<Input id="caat" bind:value={formData.caat} maxlength={10} />
						</div>
						<div class="grid gap-2">
							<Label for="carrier">Transportista (Carrier)</Label>
							<Input id="carrier" bind:value={formData.carrier} maxlength={8} />
						</div>
					</div>
					<div class="grid grid-cols-2 gap-4">
						<div class="grid gap-2">
							<Label for="transport_identification">Ident. Transporte</Label>
							<Input
								id="transport_identification"
								bind:value={formData.transport_identification}
								maxlength={20}
							/>
						</div>
						<div class="grid gap-2">
							<Label for="fast_id">FAST ID</Label>
							<Input id="fast_id" bind:value={formData.fast_id} maxlength={20} />
						</div>
					</div>
					<div class="grid gap-2">
						<Label for="shipments">Embarques (Shipments)</Label>
						<Input id="shipments" bind:value={formData.shipments} maxlength={80} />
					</div>
					<div class="grid gap-2">
						<Label for="customs_clearance">Despacho Aduanero (ID)</Label>
						<Input type="number" id="customs_clearance" bind:value={formData.customs_clearance} />
					</div>
				</Tabs.Content>

				<!-- TAB: SAT / DIGITAL -->
				<Tabs.Content value="sat" class="space-y-4 py-4">
					<div class="grid grid-cols-2 gap-4">
						<div class="grid gap-2">
							<Label for="serial_number">Número de Serie</Label>
							<Input id="serial_number" bind:value={formData.serial_number} maxlength={21} />
						</div>
						<div class="grid gap-2">
							<Label for="transaction_number">No. Transacción</Label>
							<Input
								id="transaction_number"
								bind:value={formData.transaction_number}
								maxlength={30}
							/>
						</div>
					</div>
					<div class="grid gap-2">
						<Label for="unique_badge_number">Número Único de Gafete</Label>
						<Input
							id="unique_badge_number"
							bind:value={formData.unique_badge_number}
							maxlength={250}
						/>
					</div>
					<div class="grid gap-2">
						<Label for="original_chain">Cadena Original</Label>
						<Textarea id="original_chain" bind:value={formData.original_chain} class="h-20" />
					</div>
					<div class="grid gap-2">
						<Label for="electronic_signature">Firma Electrónica</Label>
						<Textarea
							id="electronic_signature"
							bind:value={formData.electronic_signature}
							class="h-20"
						/>
					</div>
					<div class="grid gap-2">
						<Label for="sat_digital_seal">Sello Digital SAT</Label>
						<Textarea id="sat_digital_seal" bind:value={formData.sat_digital_seal} class="h-20" />
					</div>
					<div class="grid gap-2">
						<Label for="sat_original_chain">Cadena Original SAT</Label>
						<Textarea
							id="sat_original_chain"
							bind:value={formData.sat_original_chain}
							class="h-20"
						/>
					</div>
					<div class="grid grid-cols-2 gap-4">
						<div class="grid gap-2">
							<Label for="xml_doda_sent_path">Ruta XML Enviado</Label>
							<Input id="xml_doda_sent_path" bind:value={formData.xml_doda_sent_path} />
						</div>
						<div class="grid gap-2">
							<Label for="xml_doda_response_path">Ruta XML Respuesta</Label>
							<Input id="xml_doda_response_path" bind:value={formData.xml_doda_response_path} />
						</div>
					</div>
				</Tabs.Content>

				<!-- TAB: OTROS -->
				<Tabs.Content value="other" class="space-y-4 py-4">
					<div class="flex items-center space-x-2">
						<Switch id="selected" bind:checked={formData.selected} />
						<Label for="selected">Seleccionado</Label>
					</div>
					<div class="grid grid-cols-2 gap-4">
						<div class="grid gap-2">
							<Label for="user_selected">Usuario Selección</Label>
							<Input id="user_selected" bind:value={formData.user_selected} maxlength={30} />
						</div>
						<div class="grid gap-2">
							<Label for="last_user">Último Usuario</Label>
							<Input id="last_user" bind:value={formData.last_user} maxlength={30} />
						</div>
					</div>
					<div class="grid gap-2">
						<Label for="responsible">Responsable</Label>
						<Input id="responsible" bind:value={formData.responsible} maxlength={14} />
					</div>
					<div class="grid gap-2">
						<Label for="linq_sat_qr">LINQ SAT QR</Label>
						<Input id="linq_sat_qr" bind:value={formData.linq_sat_qr} maxlength={1000} />
					</div>
					<div class="grid gap-2">
						<Label for="sat_certificate">Certificado SAT</Label>
						<Input id="sat_certificate" bind:value={formData.sat_certificate} maxlength={2001} />
					</div>
				</Tabs.Content>
			</Tabs.Root>

			<Dialog.Footer class="mt-6">
				<Button type="button" variant="outline" onclick={() => (open = false)}>Cancelar</Button>
				<Button type="submit" disabled={loading}>
					{loading ? 'Guardando...' : 'Guardar'}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
