<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 {
		createElectronicNotice,
		updateElectronicNotice,
		type ElectronicNotice
	} from '$lib/api/dashboard/a76/general_catalogs/electronic-notices';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioAvisosElectrónicos } from '$lib/config/shortcuts/dashboard/general_catalogs/electronic_notices/edit';

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

	// Atajos

	const isEdit = $derived(!!item);
	const title = $derived(
		isEdit ? `Editar Aviso ${item?.notice_number || ''}` : 'Nuevo Aviso Electrónico'
	);

	// Estado del formulario
	let formData = $state({
		notice_number: '',
		year: '',
		patent: '',
		pedimento: '',
		invoice: '',
		status: '',
		validation_acknowledgment: '',
		certificate_number: '',
		file_sent: '',
		file_response: '',
		fea: ''
	});

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

	// Cargar datos
	$effect(() => {
		if (open) {
			if (item) {
				formData = {
					notice_number: item.notice_number || '',
					year: item.year || '',
					patent: item.patent || '',
					pedimento: item.pedimento || '',
					invoice: item.invoice || '',
					status: item.status || '',
					validation_acknowledgment: item.validation_acknowledgment || '',
					certificate_number: item.certificate_number || '',
					file_sent: item.file_sent || '',
					file_response: item.file_response || '',
					fea: item.fea || ''
				};
			} else {
				// Reset
				formData = {
					notice_number: '',
					year: '',
					patent: '',
					pedimento: '',
					invoice: '',
					status: '',
					validation_acknowledgment: '',
					certificate_number: '',
					file_sent: '',
					file_response: '',
					fea: ''
				};
			}
			error = null;
		}
	});

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

		loading = true;
		error = null;

		try {
			let savedNotice: ElectronicNotice | undefined;
			if (isEdit && item) {
				savedNotice = await updateElectronicNotice(item.id, formData, companyId);
			} else {
				savedNotice = await createElectronicNotice(formData, companyId);
			}

			if (!savedNotice) {
				throw new Error('No se pudo guardar el aviso electrónico');
			}

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

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

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

			<div class="grid grid-cols-2 gap-4">
				<div class="grid gap-2">
					<Label for="notice_number">No. Aviso</Label>
					<Input
						id="notice_number"
						bind:value={formData.notice_number}
						placeholder="Ej. 12345"
						maxlength={500}
					/>
				</div>
				<div class="grid gap-2">
					<Label for="year">Año</Label>
					<Input id="year" bind:value={formData.year} placeholder="Ej. 2024" maxlength={20} />
				</div>
			</div>

			<div class="grid grid-cols-2 gap-4">
				<div class="grid gap-2">
					<Label for="patent">Patente</Label>
					<Input id="patent" bind:value={formData.patent} placeholder="Ej. 1234" maxlength={4} />
				</div>
				<div class="grid gap-2">
					<Label for="pedimento">Pedimento</Label>
					<Input
						id="pedimento"
						bind:value={formData.pedimento}
						placeholder="Ej. 1234567"
						maxlength={15}
					/>
				</div>
			</div>

			<div class="grid grid-cols-2 gap-4">
				<div class="grid gap-2">
					<Label for="invoice">Factura</Label>
					<Input
						id="invoice"
						bind:value={formData.invoice}
						placeholder="Ej. F-123"
						maxlength={50}
					/>
				</div>
				<div class="grid gap-2">
					<Label for="status">Estatus</Label>
					<Input
						id="status"
						bind:value={formData.status}
						placeholder="Ej. Validado"
						maxlength={100}
					/>
				</div>
			</div>

			<div class="grid grid-cols-2 gap-4">
				<div class="grid gap-2">
					<Label for="validation_acknowledgment">Acuse Validación</Label>
					<Input
						id="validation_acknowledgment"
						bind:value={formData.validation_acknowledgment}
						placeholder="Ej. AC-123"
						maxlength={20}
					/>
				</div>
				<div class="grid gap-2">
					<Label for="certificate_number">No. Certificado</Label>
					<Input
						id="certificate_number"
						bind:value={formData.certificate_number}
						placeholder="Ej. CERT-123"
						maxlength={50}
					/>
				</div>
			</div>

			<div class="grid gap-2">
				<Label for="fea">FEA</Label>
				<Input
					id="fea"
					bind:value={formData.fea}
					placeholder="Firma Electrónica Avanzada"
					maxlength={1000}
				/>
			</div>

			<div class="grid gap-2">
				<Label for="file_sent">Archivo Enviado</Label>
				<Input
					id="file_sent"
					bind:value={formData.file_sent}
					placeholder="Nombre del archivo enviado"
					maxlength={1000}
				/>
			</div>

			<div class="grid gap-2">
				<Label for="file_response">Archivo Respuesta</Label>
				<Input
					id="file_response"
					bind:value={formData.file_response}
					placeholder="Nombre del archivo respuesta"
					maxlength={1000}
				/>
			</div>

			<Dialog.Footer>
				<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>
