<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;
		unit?: UnitOfMeasureAmerican;
		onSuccess?: () => void;
	}

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

	// Atajos

	let formData = $state({
		code: '',
		description: ''
	});

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

	async function handleSubmit(e: Event) {
		e.preventDefault();

		const activeCompanyId = companyStore.activeCompany?.id;
		if (!activeCompanyId) {
			return;
		}

		const data: UnitOfMeasureAmericanCreate | UnitOfMeasureAmericanUpdate = {
			code: formData.code,
			description: formData.description || null
		};

		const response = unit
			? await updateUnitOfMeasureAmerican(unit.id, data, activeCompanyId)
			: await createUnitOfMeasureAmerican(data, activeCompanyId);

		if (response.error) {
		} else {
			open = false;
			onSuccess?.();
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[425px]">
		<Dialog.Header>
			<Dialog.Title>{unit ? 'Editar' : 'Crear'} Unidad Americana</Dialog.Title>
		</Dialog.Header>
		<form onsubmit={handleSubmit} class="space-y-4">
			<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" />
			</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" />
			</div>
			<Dialog.Footer>
				<Button type="button" variant="outline" onclick={() => (open = false)}>Cancelar</Button>
				<Button type="submit">Guardar</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
