<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 {
		createLocation,
		updateLocation,
		type Location
	} from '$lib/api/dashboard/a76/general_catalogs/locations';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioLocalidades } from '$lib/config/shortcuts/dashboard/general_catalogs/locations/edit';

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

	// Atajos

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

	let formData = $state({
		location_code: '',
		location_description: ''
	});

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

	$effect(() => {
		if (open) {
			if (item) {
				formData = {
					location_code: item.location_code || '',
					location_description: item.location_description || ''
				};
			} else {
				formData = { location_code: '', location_description: '' };
			}
			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');

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

			const basePayload = {
				location_description: formData.location_description?.trim() || null
			};

			if (isEdit && item) {
				await updateLocation(item.id, basePayload, companyId);
			} else {
				const createPayload = {
					location_code: formData.location_code.trim(),
					...basePayload
				};
				await createLocation(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="location_code" class="text-right">Código *</Label>
						<div class="col-span-3">
							<Input
								id="location_code"
								bind:value={formData.location_code}
								maxlength={4}
								disabled={loading || isEdit}
								required
							/>
						</div>
					</div>

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