<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 {
		createUnitConversion,
		updateUnitConversion,
		type UnitConversion
	} from '$lib/api/dashboard/a76/general_catalogs/unit-conversions';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioConversiones } from '$lib/config/shortcuts/dashboard/general_catalogs/unit_conversions/edit';

	let {
		open = $bindable(false),
		conversion = null,
		mode = 'create',
		onSuccess
	}: {
		open: boolean;
		conversion?: UnitConversion | null;
		mode?: 'create' | 'edit';
		onSuccess?: () => void;
	} = $props();

	// Atajos

	const isEdit = $derived(mode === 'edit');
	const title = $derived(isEdit ? 'Editar Conversión' : 'Nueva Conversión');

	let formData = $state({
		from_unit_code: '',
		to_unit_code: '',
		conversion_factor: ''
	});

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

	$effect(() => {
		if (conversion) {
			formData = {
				from_unit_code: conversion.from_unit_code || '',
				to_unit_code: conversion.to_unit_code || '',
				conversion_factor: conversion.conversion_factor.toString() || ''
			};
		} else {
			formData = {
				from_unit_code: '',
				to_unit_code: '',
				conversion_factor: ''
			};
		}
	});

	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.from_unit_code.trim()) throw new Error('El código origen es requerido');
			if (!formData.to_unit_code.trim()) throw new Error('El código destino es requerido');
			if (!formData.conversion_factor || formData.conversion_factor === '')
				throw new Error('El factor de conversión es requerido');

			const dataToSend = {
				from_unit_code: formData.from_unit_code.trim(),
				to_unit_code: formData.to_unit_code.trim(),
				conversion_factor: parseFloat(formData.conversion_factor)
			};

			if (isNaN(dataToSend.conversion_factor)) {
				throw new Error('El factor de conversión debe ser un número válido');
			}

			if (isEdit && conversion) {
				await updateUnitConversion(conversion.id, dataToSend, companyId);
			} else {
				await createUnitConversion(dataToSend, companyId);
			}

			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="from_unit_code">Código origen <span class="text-destructive">*</span></Label>
					<Input
						id="from_unit_code"
						bind:value={formData.from_unit_code}
						maxlength={5}
						disabled={loading}
						required
					/>
				</div>

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

				<div class="grid gap-2">
					<Label for="conversion_factor"
						>Factor de conversión <span class="text-destructive">*</span></Label
					>
					<Input
						id="conversion_factor"
						type="number"
						step="0.000001"
						bind:value={formData.conversion_factor}
						disabled={loading}
						required
					/>
				</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>
