<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 {
		UnitOfMeasureCustoms,
		UnitOfMeasureCustomsCreate,
		UnitOfMeasureCustomsUpdate
	} from '$lib/api/dashboard/a76/general_catalogs/units-of-measure';
	import {
		createUnitOfMeasureCustoms,
		updateUnitOfMeasureCustoms
	} from '$lib/api/dashboard/a76/general_catalogs/units-of-measure';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioUnidadesAduanas } from '$lib/config/shortcuts/dashboard/general_catalogs/units_of_measure/customs/edit';

	interface Props {
		open: boolean;
		unit?: UnitOfMeasureCustoms;
		onSuccess?: () => void;
	}

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

	// Atajos

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

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

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

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

		const data: UnitOfMeasureCustomsCreate | UnitOfMeasureCustomsUpdate = {
			code: formData.code,
			description: formData.description || null,
			scaii_unit_code: formData.scaii_unit_code || null
		};

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