<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'; // Para que quepa más texto en la firma
	// 👇 Verifica tu ruta de importación
	import {
		createSignature,
		updateSignature,
		type Signature
	} from '$lib/api/dashboard/a76/general_catalogs/signatures';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioFirmas } from '$lib/config/shortcuts/dashboard/general_catalogs/signatures/edit';

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

	// Atajos

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

	// Estado del formulario
	let formData = $state({
		code: '',
		signature: '',
		photo_path: ''
	});

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

	// Cargar datos al abrir
	$effect(() => {
		if (open) {
			if (item) {
				formData = {
					code: item.code,
					signature: item.signature || '',
					photo_path: item.photo_path || ''
				};
			} else {
				formData = {
					code: '',
					signature: '',
					photo_path: ''
				};
			}
			error = null;
		}
	});

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

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

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

			// Preparar datos
			const dataToSend = {
				code: formData.code.trim(),
				signature: formData.signature.trim() || null,
				photo_path: formData.photo_path.trim() || null
			};

			let response;

			// 👇 companyId por fuera (Argumento separado)
			if (isEdit && item) {
				response = await updateSignature(item.id, dataToSend, companyId);
			} else {
				response = await createSignature(dataToSend, companyId);
			}

			open = false;
			if (onSuccess) onSuccess();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Error al guardar la firma';
		} 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="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 <span class="text-destructive">*</span></Label
					>
					<div class="col-span-3">
						<Input
							id="code"
							bind:value={formData.code}
							placeholder="Ej: REP_LEGAL"
							maxlength={10}
							disabled={loading || isEdit}
							required
						/>
						<p class="text-[10px] text-muted-foreground mt-1">Máximo 10 caracteres.</p>
					</div>
				</div>

				<div class="grid grid-cols-4 items-center gap-4">
					<Label for="signature" class="text-right">Firma / Nombre</Label>
					<div class="col-span-3">
						<Textarea
							id="signature"
							bind:value={formData.signature}
							placeholder="Ej: Juan Pérez - Representante Legal"
							maxlength={1000}
							disabled={loading}
						/>
					</div>
				</div>

				<div class="grid grid-cols-4 items-center gap-4">
					<Label for="photo_path" class="text-right">Ruta Foto</Label>
					<div class="col-span-3">
						<Input
							id="photo_path"
							bind:value={formData.photo_path}
							placeholder="Ej: /uploads/firmas/juan.png"
							maxlength={1000}
							disabled={loading}
						/>
						<p class="text-[10px] text-muted-foreground mt-1">Ruta del archivo (Texto).</p>
					</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.Root>
