<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 { companyStore } from '$lib/stores/company.svelte';
	import { createINPC, updateINPC, type INPC } from '$lib/api/dashboard/a76/general_catalogs/inpc';
	import { obtenerAtajosFormularioInpc } from '$lib/config/shortcuts/dashboard/general_catalogs/inpc/edit';

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

	const isEdit = $derived(!!item);
	const title = $derived(isEdit ? `Editar INPC ${item?.year}-${item?.month}` : 'Nuevo INPC');

	// Estado del formulario
	let formData = $state({
		year: '',
		month: '',
		value: ''
	});

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

	// Cargar datos
	$effect(() => {
		if (open) {
			if (item) {
				formData = {
					year: item.year || '',
					month: item.month || '',
					value: item.value?.toString() || ''
				};
			} else {
				// Reset
				formData = {
					year: '',
					month: '',
					value: ''
				};
			}
			error = null;
		}
	});

	async function handleSubmit() {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) {
			error = 'No hay compañía seleccionada';
			return;
		}

		loading = true;
		error = null;

		try {
			const payload = {
				year: formData.year,
				month: formData.month,
				value: formData.value ? parseFloat(formData.value) : undefined
			};

			if (isEdit && item) {
				await updateINPC(item.id, payload, companyId);
			} else {
				await createINPC(payload, companyId);
			}

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

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[500px]">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
		</Dialog.Header>

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

			<div class="grid grid-cols-4 items-center gap-4">
				<Label for="year" class="text-right">Año</Label>
				<Input id="year" bind:value={formData.year} class="col-span-3" maxlength={4} required />
			</div>

			<div class="grid grid-cols-4 items-center gap-4">
				<Label for="month" class="text-right">Mes</Label>
				<Input
					id="month"
					bind:value={formData.month}
					class="col-span-3"
					maxlength={2}
					required
					placeholder="01-12"
				/>
			</div>

			<div class="grid grid-cols-4 items-center gap-4">
				<Label for="value" class="text-right">Valor</Label>
				<Input
					id="value"
					type="number"
					step="0.00000001"
					bind:value={formData.value}
					class="col-span-3"
				/>
			</div>

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