<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 * as Select from '$lib/components/ui/select';
	import {
		createErrorCatalog,
		updateErrorCatalog,
		getErrorClassifications,
		type ErrorCatalog,
		type ErrorClassification
	} from '$lib/api/dashboard/a76/general_catalogs/error-catalogs';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioErrores } from '$lib/config/shortcuts/dashboard/general_catalogs/error_catalogs/edit';

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

	// Atajos

	const isEdit = $derived(!!item);
	const title = $derived(isEdit ? 'Editar Error' : 'Nuevo Error');

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

	let loading = $state(false);
	let error = $state<string | null>(null);
	let classifications = $state<ErrorClassification[]>([]);
	let loadingClassifications = $state(false);

	$effect(() => {
		if (open) {
			if (item) {
				formData = {
					code: item.code || '',
					description: item.description || '',
					classification_id: item.classification_id ? String(item.classification_id) : ''
				};
			} else {
				formData = { code: '', description: '', classification_id: '' };
			}
			error = null;
			loadClassifications();
		}
	});

	async function loadClassifications() {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;
		loadingClassifications = true;
		try {
			const response = await getErrorClassifications(companyId, 1, 100);
			classifications = response.items || [];
		} catch (err) {
			console.error('Error loading classifications', err);
		} finally {
			loadingClassifications = false;
		}
	}

	async function handleSubmit() {
		loading = true;
		error = null;
		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) throw new Error('No hay una compañía seleccionada');

			if (!formData.code.trim()) throw new Error('El código es requerido');

			const basePayload = {
				description: formData.description?.trim() || null,
				classification_id: formData.classification_id ? Number(formData.classification_id) : null
			};

			if (isEdit && item) {
				await updateErrorCatalog(item.id, basePayload, companyId);
			} else {
				const createPayload = {
					code: formData.code.trim(),
					...basePayload
				};
				await createErrorCatalog(createPayload, 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.Portal>
		<Dialog.Overlay class="fixed inset-0 z-[9999] bg-black/80 backdrop-blur-sm" />

		<Dialog.Content
			class="fixed left-[50%] top-[50%] z-[10000] w-full max-w-[520px] translate-x-[-50%] translate-y-[-50%] border bg-background p-6 shadow-lg sm:rounded-lg"
		>
			<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">Código *</Label>
						<div class="col-span-3">
							<Input
								id="code"
								bind:value={formData.code}
								maxlength={15}
								disabled={loading || isEdit}
								required
							/>
						</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">
							<Input
								id="description"
								bind:value={formData.description}
								maxlength={255}
								disabled={loading}
							/>
						</div>
					</div>

					<div class="grid grid-cols-4 items-center gap-4">
						<Label for="classification" class="text-right">Clasificación</Label>
						<div class="col-span-3">
							<Select.Root
								bind:value={formData.classification_id}
								disabled={loading || loadingClassifications}
							>
								<Select.Trigger>
									{#if formData.classification_id}
										{#each classifications as classification (classification.id)}
											{#if String(classification.id) === formData.classification_id}
												{classification.code}{#if classification.level}
													- {classification.level}{/if}
											{/if}
										{/each}
									{:else}
										<span class="text-muted-foreground">
											{loadingClassifications ? 'Cargando...' : 'Seleccione una clasificación'}
										</span>
									{/if}
								</Select.Trigger>
								<Select.Content>
									<Select.Item value="">Sin clasificación</Select.Item>
									{#each classifications as classification (classification.id)}
										<Select.Item value={String(classification.id)}>
											{classification.code}{#if classification.level}
												- {classification.level}{/if}
										</Select.Item>
									{/each}
								</Select.Content>
							</Select.Root>
						</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.Portal>
</Dialog.Root>
