<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 { Textarea } from '$lib/components/ui/textarea';
	import {
		createLegend,
		updateLegend,
		type Legend
	} from '$lib/api/dashboard/a76/general_catalogs/legends';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioLeyendas } from '$lib/config/shortcuts/dashboard/general_catalogs/legends/edit';

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

	// Atajos

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

	// Estado del formulario
	// code es number | null para manejar el input type="number"
	let formData = $state({
		code: null as number | null,
		description: ''
	});

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

	// Cargar datos al abrir
	$effect(() => {
		if (open) {
			if (item) {
				formData = {
					code: item.code, // Es number
					description: item.description || ''
				};
			} else {
				formData = {
					code: null,
					description: ''
				};
			}
			error = null;
		}
	});

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

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

			// Validaciones
			if (formData.code === null) throw new Error('La Clave (Código) es requerida');

			// Preparar datos
			const dataToSend = {
				code: Number(formData.code), // Aseguramos que sea número
				description: formData.description.trim() || undefined
			};

			let response;

			if (isEdit && item) {
				response = await updateLegend(item.id, dataToSend, companyId);
			} else {
				response = await createLegend(dataToSend, companyId);
			}

			// Verificar si hubo error
			if (response.error) {
				throw new Error(response.error);
			}

			open = false;
			if (onSuccess) onSuccess();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Error al guardar la leyenda';
		} 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="space-y-4 py-4"
		>
			{#if error}
				<div class="rounded-md bg-destructive/15 p-3 text-sm text-destructive">
					{error}
				</div>
			{/if}

			<div class="grid gap-4">
				<div class="grid grid-cols-4 items-center gap-4">
					<Label for="code" class="text-right">Clave <span class="text-destructive">*</span></Label>
					<div class="col-span-3">
						<Input
							id="code"
							type="number"
							bind:value={formData.code}
							placeholder="Ej: 10"
							disabled={loading}
							required
						/>
						<p class="text-[10px] text-muted-foreground mt-1">Debe ser un número entero.</p>
					</div>
				</div>

				<div class="grid grid-cols-4 items-center gap-4">
					<Label for="description" class="text-right">Descripción</Label>
					<div class="col-span-3">
						<Textarea
							id="description"
							bind:value={formData.description}
							placeholder="Ej: Esta leyenda aplica para..."
							maxlength={2000}
							disabled={loading}
							class="min-h-[100px]"
						/>
						<p class="text-[10px] text-muted-foreground mt-1 text-right">
							{formData.description.length}/2000
						</p>
					</div>
				</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>
