<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 {
		createUnitOfMeasureACE,
		updateUnitOfMeasureACE,
		type UnitOfMeasureACE
	} from '$lib/api/dashboard/a76/general_catalogs/units-of-measure';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioUnidadesACE } from '$lib/config/shortcuts/dashboard/general_catalogs/units_of_measure/ace/edit';

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

	// Atajos

	const isEdit = $derived(!!item);
	const title = $derived(isEdit ? 'Editar Unidad ACE' : 'Nueva Unidad ACE');

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

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

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

	async function handleSubmit() {
		loading = true;
		error = null;

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

			if (!formData.code.trim()) throw new Error('El código es requerido');

			const dataToSend = {
				code: formData.code.trim(),
				description: formData.description.trim() || null
			};

			let response;
			if (isEdit && item) {
				response = await updateUnitOfMeasureACE(item.id, dataToSend, companyId);
			} else {
				response = await createUnitOfMeasureACE(dataToSend, companyId);
			}

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

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

<Dialog.Root bind:open>
	<Dialog.Content class="max-w-md">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
		</Dialog.Header>

		<form
			onsubmit={(e) => {
				e.preventDefault();
				handleSubmit();
			}}
			class="space-y-4"
		>
			{#if error}
				<div class="p-3 text-sm text-destructive bg-destructive/10 rounded-md">
					{error}
				</div>
			{/if}

			<div class="grid gap-4 py-4">
				<div class="grid gap-2">
					<Label for="code">Código <span class="text-destructive">*</span></Label>
					<Input id="code" bind:value={formData.code} maxlength={4} disabled={loading} required />
				</div>

				<div class="grid gap-2">
					<Label for="description">Descripción</Label>
					<Input
						id="description"
						bind:value={formData.description}
						maxlength={49}
						disabled={loading}
					/>
				</div>
			</div>

			<Dialog.Footer>
				<Button type="button" variant="outline" onclick={() => (open = false)} disabled={loading}>
					Cancelar
				</Button>
				<Button type="submit" disabled={loading}>
					{loading ? 'Guardando...' : isEdit ? 'Actualizar' : 'Crear'}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
