<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 {
		UnitOfMeasureOMA,
		UnitOfMeasureOMACreate,
		UnitOfMeasureOMAUpdate
	} from '$lib/api/dashboard/a76/general_catalogs/units-of-measure';
	import {
		createUnitOfMeasureOMA,
		updateUnitOfMeasureOMA
	} from '$lib/api/dashboard/a76/general_catalogs/units-of-measure';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioUnidadesOMA } from '$lib/config/shortcuts/dashboard/general_catalogs/units_of_measure/oma/edit';

	interface Props {
		open: boolean;
		unit?: UnitOfMeasureOMA;
		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: UnitOfMeasureOMACreate | UnitOfMeasureOMAUpdate = {
			code: formData.code,
			description: formData.description || null
		};

		const response = unit
			? await updateUnitOfMeasureOMA(unit.id, data, activeCompanyId)
			: await createUnitOfMeasureOMA(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 OMA</Dialog.Title>
		</Dialog.Header>
		<form onsubmit={handleSubmit} class="space-y-4">
			<div class="space-y-2">
				<Label for="code">Código * (máx. 10 caracteres)</Label>
				<Input id="code" bind:value={formData.code} required maxlength="10" />
			</div>
			<div class="space-y-2">
				<Label for="description">Descripción (máx. 200 caracteres)</Label>
				<Input id="description" bind:value={formData.description} maxlength="200" />
			</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>
