<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 { companyStore } from '$lib/stores/company.svelte';
	import {
		createPrevalidator,
		updatePrevalidator,
		type Prevalidator
	} from '$lib/api/dashboard/a76/general_catalogs/prevalidators';
	import { obtenerAtajosFormularioPrevalidadores } from '$lib/config/shortcuts/dashboard/general_catalogs/prevalidators/edit';

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

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

	// Atajos

	// Estado del formulario
	let formData = $state({
		code: '',
		description: '',
		customs_prevalidator: '',
		patent_prevalidator: ''
	});

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

	// Cargar datos
	$effect(() => {
		if (open) {
			if (item) {
				formData = {
					code: item.code || '',
					description: item.description || '',
					customs_prevalidator: item.customs_prevalidator || '',
					patent_prevalidator: item.patent_prevalidator || ''
				};
			} else {
				// Reset
				formData = {
					code: '',
					description: '',
					customs_prevalidator: '',
					patent_prevalidator: ''
				};
			}
			error = null;
		}
	});

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

		loading = true;
		error = null;

		try {
			if (isEdit && item) {
				await updatePrevalidator(item.id, formData, companyId);
			} else {
				await createPrevalidator(formData, companyId);
			}

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

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[500px]">
		<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 gap-2">
				<Label for="code">Código</Label>
				<Input id="code" bind:value={formData.code} placeholder="Ej. 123" maxlength={20} />
			</div>

			<div class="grid gap-2">
				<Label for="description">Descripción</Label>
				<Input
					id="description"
					bind:value={formData.description}
					placeholder="Descripción del prevalidador"
					maxlength={50}
				/>
			</div>

			<div class="grid grid-cols-2 gap-4">
				<div class="grid gap-2">
					<Label for="customs_prevalidator">Aduana</Label>
					<Input
						id="customs_prevalidator"
						bind:value={formData.customs_prevalidator}
						placeholder="Ej. 123"
						maxlength={20}
					/>
				</div>
				<div class="grid gap-2">
					<Label for="patent_prevalidator">Patente</Label>
					<Input
						id="patent_prevalidator"
						bind:value={formData.patent_prevalidator}
						placeholder="Ej. 1234"
						maxlength={20}
					/>
				</div>
			</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>
