<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,
		type LocationSystem
	} 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,
		canMutate = true,
		onSuccess
	}: {
		open: boolean;
		item?: Location | null;
		canMutate?: boolean;
		onSuccess?: () => void;
	} = $props();

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

	const systemOptions: { value: LocationSystem; label: string }[] = [
		{ value: 'fixed_asset', label: 'Activo fijo (FA)' },
		{ value: 'inventory', label: 'Inventario' }
	];

	let formData = $state({
		clave_localizacion: '',
		localizacion: '',
		system: 'fixed_asset' as LocationSystem
	});

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

	$effect(() => {
		if (open) {
			if (item) {
				formData = {
					clave_localizacion: item.clave_localizacion ?? '',
					localizacion: item.localizacion ?? '',
					system: item.system ?? 'fixed_asset'
				};
			} else {
				formData = {
					clave_localizacion: '',
					localizacion: '',
					system: 'fixed_asset'
				};
			}
			error = null;
		}
	});

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

			if (!formData.clave_localizacion.trim()) throw new Error('La clave es requerida');

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

			if (isEdit && item) {
				await updateLocation(
					item.id,
					{
						...basePayload,
						clave_localizacion: formData.clave_localizacion.trim(),
						system: formData.system
					},
					companyId
				);
			} else {
				await createLocation(
					{
						clave_localizacion: formData.clave_localizacion.trim(),
						...basePayload,
						system: formData.system
					},
					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="clave_localizacion" class="text-right">Clave *</Label>
						<div class="col-span-3">
							<Input
								id="clave_localizacion"
								bind:value={formData.clave_localizacion}
								maxlength={20}
								disabled={loading || isEdit || !canMutate}
								required
							/>
						</div>
					</div>

					<div class="grid grid-cols-4 items-center gap-4">
						<Label for="localizacion" class="text-right">Localización</Label>
						<div class="col-span-3">
							<Input
								id="localizacion"
								bind:value={formData.localizacion}
								maxlength={200}
								disabled={loading || !canMutate}
							/>
						</div>
					</div>

					<div class="grid grid-cols-4 items-center gap-4">
						<Label for="system" class="text-right">Sistema</Label>
						<div class="col-span-3">
							<select
								id="system"
								bind:value={formData.system}
								disabled={loading || !canMutate}
								class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
							>
								{#each systemOptions as opt}
									<option value={opt.value}>{opt.label}</option>
								{/each}
							</select>
						</div>
					</div>
				</div>

				<Dialog.Footer>
					<Button type="button" variant="outline" onclick={() => (open = false)} disabled={loading}>
						Cancelar
					</Button>
					<Button type="submit" disabled={loading || !canMutate}>
						{loading ? 'Guardando...' : isEdit ? 'Actualizar' : 'Crear'}
					</Button>
				</Dialog.Footer>
			</form>
		</Dialog.Content>
	</Dialog.Portal>
</Dialog.Root>
