<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 {
		createEquivalency,
		updateEquivalency,
		type Equivalency
	} from '$lib/api/dashboard/a76/general_catalogs/equivalencies';
	import { obtenerAtajosFormularioEquivalencias } from '$lib/config/shortcuts/dashboard/general_catalogs/equivalencies/edit';

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

	// Atajos

	const isEdit = $derived(!!item);
	const title = $derived(
		isEdit ? `Editar Equivalencia ${item?.fraccion_mex || ''}` : 'Nueva Equivalencia'
	);

	// Estado del formulario
	let formData = $state({
		fraccion_mex: '',
		fraccion_us: '',
		description: ''
	});

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

	// Cargar datos
	$effect(() => {
		if (open) {
			if (item) {
				formData = {
					fraccion_mex: item.fraccion_mex || '',
					fraccion_us: item.fraccion_us || '',
					description: item.description || ''
				};
			} else {
				// Reset
				formData = {
					fraccion_mex: '',
					fraccion_us: '',
					description: ''
				};
			}
			error = null;
		}
	});

	async function handleSubmit() {
		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 updateEquivalency(item.id, formData, companyId);
			} else {
				response = await createEquivalency(formData, companyId);
			}

			if (response.error) {
				throw new Error(response.error);
			}

			open = false;
			if (onSuccess) onSuccess();
		} catch (e) {
			console.error(e);
			error = e instanceof Error ? e.message : 'Error al guardar equivalencia';
		} 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 grid-cols-4 items-center gap-4">
				<Label for="fraccion_mex" class="text-right">Fracción MX</Label>
				<Input
					id="fraccion_mex"
					bind:value={formData.fraccion_mex}
					class="col-span-3"
					maxlength={10}
					required
					placeholder="Ej. 8544.11.01"
				/>
			</div>

			<div class="grid grid-cols-4 items-center gap-4">
				<Label for="fraccion_us" class="text-right">Fracción US</Label>
				<Input
					id="fraccion_us"
					bind:value={formData.fraccion_us}
					class="col-span-3"
					maxlength={100}
					required
					placeholder="Ej. 8544.11.00"
				/>
			</div>

			<div class="grid grid-cols-4 items-center gap-4">
				<Label for="description" class="text-right">Descripción</Label>
				<Input
					id="description"
					bind:value={formData.description}
					class="col-span-3"
					maxlength={200}
				/>
			</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>
