<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';
	// 👇 1. Importamos la API correcta
	import {
		updateClassificationConcept,
		createClassificationConcept,
		type ClassificationConcept
	} from '$lib/api/dashboard/a76/general_catalogs/classification-concepts';
	// 👇 2. Importamos el Store para el ID de la empresa
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioClasificacion } from '$lib/config/shortcuts/dashboard/general_catalogs/classification/edit';

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

	// Atajos

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

	// 👇 3. Estado limpio: Solo lo que existe en la BD
	let formData = $state({
		classification: '',
		description: ''
	});

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

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

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

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

			// Validar campos
			if (!formData.classification.trim())
				throw new Error('El nombre de la clasificación es requerido');

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

			// 👇 5. Llamar a la API pasando el companyId
			if (isEdit && item) {
				await updateClassificationConcept(item.id, dataToSend, companyId);
			} else {
				await createClassificationConcept(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="classification">Clasificación <span class="text-destructive">*</span></Label>
					<Input
						id="classification"
						bind:value={formData.classification}
						placeholder="Ej: GENERAL"
						maxlength={30}
					/>
				</div>
				<div class="grid gap-2">
					<Label for="description">Descripción</Label>
					<Input
						id="description"
						bind:value={formData.description}
						placeholder="Ej: Descripción general"
						maxlength={255}
					/>
				</div>
			</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>
