<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 { companyStore } from '$lib/stores/company.svelte';
	import type { Equivalency } from '$lib/api/dashboard/a76/general_catalogs/equivalencies';
	import {
		createEquivalency,
		updateEquivalency
	} from '$lib/api/dashboard/a76/general_catalogs/equivalencies';

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

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

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

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

	$effect(() => {
		if (!open) return;
		if (item) {
			formData = {
				identifier: item.identifier || '',
				description: item.description || ''
			};
		} else {
			formData = {
				identifier: '',
				description: ''
			};
		}
		error = null;
	});

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

		loading = true;
		error = null;

		try {
			if (!formData.identifier.trim()) throw new Error('Identificador requerido');
			if (formData.identifier.trim().length > 10)
				throw new Error('El identificador no puede exceder 10 caracteres');

			const dataToSend = {
				identifier: formData.identifier.trim(),
				description: formData.description.trim() ? formData.description.trim() : null
			};

			const response = isEdit && item
				? await updateEquivalency(item.id, dataToSend, companyId)
				: await createEquivalency(dataToSend, companyId);

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

			open = false;
			// Proceso 1: si fue INSERT, encadenamos a DATOS DE EQUIVALENTES.
			if (!isEdit && response.data) onSuccess?.(response.data);
			else onSuccess?.();
		} catch (e) {
			console.error(e);
			error = e instanceof Error ? e.message : 'Error al guardar la equivalencia';
		} finally {
			loading = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[520px]">
		<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 gap-4 py-4">
				<div class="grid gap-2">
					<Label for="identifier">
						Identificador <span class="text-destructive">*</span>
					</Label>
					<Input
						id="identifier"
						bind:value={formData.identifier}
						disabled={loading}
						maxlength={10}
						required
						placeholder="Ej: KGM, PCS, MP..."
					/>
				</div>

				<div class="grid gap-2">
					<Label for="description">Descripción</Label>
					<Textarea
						id="description"
						bind:value={formData.description}
						disabled={loading}
						maxlength={200}
						class="min-h-[100px]"
						placeholder="(opcional)"
					/>
				</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>

