<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 { obtenerAtajosFormularioIdentificadores } from '$lib/config/shortcuts/dashboard/general_catalogs/identifiers/edit';
	import {
		createIdentifier,
		updateIdentifier,
		type Identifier
	} from '$lib/api/dashboard/a76/general_catalogs/identifiers';

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

	// Atajos

	const isEdit = $derived(!!item);
	const title = $derived(
		isEdit ? `Editar Identificador ${item?.code || ''}` : 'Nuevo Identificador'
	);

	// Estado del formulario
	let formData = $state({
		code: '',
		description: '',
		level: '',
		complement: ''
	});

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

	// Cargar datos
	$effect(() => {
		if (open) {
			if (item) {
				formData = {
					code: item.code || '',
					description: item.description || '',
					level: item.level || '',
					complement: item.complement || ''
				};
			} else {
				// Reset
				formData = {
					code: '',
					description: '',
					level: '',
					complement: ''
				};
			}
			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 (isEdit && item) {
				await updateIdentifier(item.id, formData, companyId);
			} else {
				await createIdentifier(formData, companyId);
			}

			open = false;
			if (onSuccess) onSuccess();
		} catch (e) {
			console.error(e);
			error = e instanceof Error ? e.message : 'Error al guardar identificador';
		} 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 gap-2">
				<Label for="code">Clave</Label>
				<Input id="code" bind:value={formData.code} placeholder="Ej. AI" maxlength={2} required />
			</div>

			<div class="grid gap-2">
				<Label for="description">Descripción</Label>
				<Input
					id="description"
					bind:value={formData.description}
					placeholder="Descripción del identificador"
					maxlength={1000}
				/>
			</div>

			<div class="grid gap-2">
				<Label for="level">Nivel</Label>
				<Input id="level" bind:value={formData.level} placeholder="Ej. G" maxlength={1} />
			</div>

			<div class="grid gap-2">
				<Label for="complement">Complemento</Label>
				<Input
					id="complement"
					bind:value={formData.complement}
					placeholder="Información complementaria"
					maxlength={5000}
				/>
			</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>
