<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 { LoaderCircle } from 'lucide-svelte';
	import type { Seal } from '$lib/api/dashboard/a76/general_catalogs/seals';
	import { createSeal, updateSeal } from '$lib/api/dashboard/a76/general_catalogs/seals';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioSellos } from '$lib/config/shortcuts/dashboard/general_catalogs/seal/edit';

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

	// Atajos

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

	let formData = $state({
		seal: ''
	});

	const isEdit = $derived(!!item);
	const title = $derived(isEdit ? 'Editar Sello' : 'Crear Sello');
	const submitText = $derived(isEdit ? 'Guardar Cambios' : 'Crear');

	// Reset form when dialog opens/closes or item changes
	$effect(() => {
		if (open && item) {
			formData.seal = item.seal;
		} else if (!open) {
			// Reset when closing
			formData.seal = '';
			error = null;
		}
	});

	async function handleSubmit(e: Event) {
		e.preventDefault();

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

		loading = true;
		error = null;

		try {
			let response;

			if (isEdit && item) {
				response = await updateSeal(item.id, formData, companyId);
			} else {
				response = await createSeal(formData, companyId);
			}

			if (onSuccess) {
				onSuccess(response.data);
			}

			open = false;
		} catch (err: any) {
			error = err.message || 'Error al guardar el sello';
			console.error('Error saving seal:', err);
		} finally {
			loading = false;
		}
	}

	function handleCancel() {
		open = false;
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[500px]">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
			<Dialog.Description>
				{#if isEdit}
					Modifica los datos del sello
				{:else}
					Ingresa los datos del nuevo sello
				{/if}
			</Dialog.Description>
		</Dialog.Header>

		<form onsubmit={handleSubmit} class="space-y-4">
			<div class="space-y-2">
				<Label for="seal">
					Sello <span class="text-destructive">*</span>
				</Label>
				<Input
					id="seal"
					bind:value={formData.seal}
					placeholder="Ej: SEAL123456"
					maxlength={15}
					required
					disabled={loading}
				/>
				<p class="text-xs text-muted-foreground">Máximo 15 caracteres</p>
			</div>

			{#if error}
				<div class="rounded-md bg-destructive/15 p-3">
					<p class="text-sm text-destructive">{error}</p>
				</div>
			{/if}

			<Dialog.Footer>
				<Button type="button" variant="outline" onclick={handleCancel} disabled={loading}>
					Cancelar
				</Button>
				<Button type="submit" disabled={loading}>
					{#if loading}
						<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
					{/if}
					{submitText}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
