<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 type {
		UnitOfMeasureAmerican,
		UnitOfMeasureAmericanCreate,
		UnitOfMeasureAmericanUpdate
	} from '$lib/api/dashboard/a76/general_catalogs/units-of-measure';
	import {
		createUnitOfMeasureAmerican,
		updateUnitOfMeasureAmerican
	} from '$lib/api/dashboard/a76/general_catalogs/units-of-measure';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioUnidadesAmericanas } from '$lib/config/shortcuts/dashboard/general_catalogs/units_of_measure/american/edit';

	interface Props {
		open: boolean;
		item?: UnitOfMeasureAmerican | null;
		onSuccess?: () => void;
	}

	let { open = $bindable(), item, onSuccess }: Props = $props();

	// Atajos

	let formData = $state({
		code: '',
		description: ''
	});
	let loading = $state(false);
	let error = $state<string | null>(null);

	$effect(() => {
		if (open) {
			if (item) {
				formData = {
					code: item.code,
					description: item.description || ''
				};
			} else {
				formData = { code: '', description: '' };
			}
			error = null;
		}
	});

	async function handleSubmit(e: Event) {
		e.preventDefault();
		loading = true;
		error = null;

		try {
			const activeCompanyId = companyStore.activeCompany?.id;
			if (!activeCompanyId) {
				throw new Error('No hay una compañía seleccionada');
			}

			let response;
			if (item) {
				response = await updateUnitOfMeasureAmerican(
					item.id,
					{
						code: formData.code,
						description: formData.description || null
					} satisfies UnitOfMeasureAmericanUpdate,
					activeCompanyId
				);
			} else {
				response = await createUnitOfMeasureAmerican(
					{
						code: formData.code,
						description: formData.description || null
					} satisfies UnitOfMeasureAmericanCreate,
					activeCompanyId
				);
			}

			if (response.error) {
				throw new Error(response.error);
			}

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

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[425px]">
		<Dialog.Header>
			<Dialog.Title>{item ? 'Editar' : 'Crear'} Unidad Americana</Dialog.Title>
		</Dialog.Header>
		<form onsubmit={handleSubmit} class="space-y-4">
			{#if error}
				<div class="rounded-md bg-destructive/15 p-3 text-sm text-destructive">{error}</div>
			{/if}
			<div class="space-y-2">
				<Label for="code">Código * (máx. 3 caracteres)</Label>
				<Input id="code" bind:value={formData.code} required maxlength={3} disabled={loading} />
			</div>
			<div class="space-y-2">
				<Label for="description">Descripción (máx. 40 caracteres)</Label>
				<Input id="description" bind:value={formData.description} maxlength={40} disabled={loading} />
			</div>
			<Dialog.Footer>
				<Button type="button" variant="outline" onclick={() => (open = false)} disabled={loading}
					>Cancelar</Button
				>
				<Button type="submit" disabled={loading}>{loading ? 'Guardando...' : 'Guardar'}</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
