<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 { statesApi, type State, type CreateStateData, type UpdateStateData } from "$lib/api/dashboard/reference_data/states";
	import { LoaderCircle } from 'lucide-svelte';

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

	let formData = $state({
		m3_key: "",
		description: "",
		mex_key: "",
		ame_key: ""
	});

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

	// Actualizar formData cuando item cambia
	$effect(() => {
		if (item) {
			formData = {
				m3_key: item.m3_key,
				description: item.description,
				mex_key: item.mex_key || "",
				ame_key: item.ame_key || ""
			};
		} else {
			formData = {
				m3_key: "",
				description: "",
				mex_key: "",
				ame_key: ""
			};
		}
	});

	const isEditing = $derived(!!item);

	async function handleSubmit(e: Event) {
		e.preventDefault();
		loading = true;
		error = null;

		try {
			let response;
			if (isEditing && item) {
				const payload: UpdateStateData = {
					m3_key: formData.m3_key,
					description: formData.description,
					mex_key: formData.mex_key || null,
					ame_key: formData.ame_key || null
				};
				response = await statesApi.update(item.m3_key, payload);
			} else {
				const payload: CreateStateData = {
					m3_key: formData.m3_key,
					description: formData.description,
					mex_key: formData.mex_key || null,
					ame_key: formData.ame_key || null
				};
				response = await statesApi.create(payload);
			}

			if (response.error) {
				if (response.status === 401) {
					error = 'Sesión expirada. Recargando página...';
					setTimeout(() => {
						window.location.reload();
					}, 1500);
				} else {
					error = response.error;
				}
				return;
			}

			// Éxito
			open = false;
			if (onSuccess) {
				onSuccess();
			}
		} catch (e) {
			error = e instanceof Error ? e.message : "Error al guardar";
			console.error("Error saving:", e);
		} finally {
			loading = false;
		}
	}

	function handleOpenChange(newOpen: boolean) {
		if (!newOpen) {
			// Limpiar form al cerrar
			formData = {
				m3_key: "",
				description: "",
				mex_key: "",
				ame_key: ""
			};
			error = null;
		}
		open = newOpen;
	}
</script>

<Dialog.Root bind:open onOpenChange={handleOpenChange}>
	<Dialog.Content class="sm:max-w-[600px]">
		<Dialog.Header>
			<Dialog.Title>
				{isEditing ? "Editar" : "Nuevo"} Estado
			</Dialog.Title>
			<Dialog.Description>
				{isEditing 
					? "Modifica los datos del estado."
					: "Completa los datos para crear un nuevo estado."}
			</Dialog.Description>
		</Dialog.Header>

		<form onsubmit={handleSubmit} class="space-y-4">
			{#if error}
				<div class="rounded-lg border border-destructive bg-destructive/10 p-3 text-sm text-destructive">
					{error}
				</div>
			{/if}

			<div class="grid grid-cols-2 gap-4">
				<div class="space-y-2">
					<Label for="m3_key">Clave M3 *</Label>
					<Input
						id="m3_key"
						bind:value={formData.m3_key}
						placeholder="Ej: AGS"
						maxlength={3}
						required
						disabled={loading || isEditing}
					/>
					<p class="text-sm text-muted-foreground">Clave de hasta 3 caracteres</p>
				</div>

				<div class="space-y-2">
					<Label for="description">Descripción *</Label>
					<Input
						id="description"
						bind:value={formData.description}
						placeholder="Ej: Aguascalientes"
						maxlength={50}
						required
						disabled={loading}
					/>
				</div>
			</div>

			<div class="grid grid-cols-2 gap-4">
				<div class="space-y-2">
					<Label for="mex_key">Clave MEX (opcional)</Label>
					<Input
						id="mex_key"
						bind:value={formData.mex_key}
						placeholder="Ej: AGS"
						maxlength={3}
						disabled={loading}
					/>
					<p class="text-sm text-muted-foreground">Clave mexicana (hasta 3 caracteres)</p>
				</div>

				<div class="space-y-2">
					<Label for="ame_key">Clave AME (opcional)</Label>
					<Input
						id="ame_key"
						bind:value={formData.ame_key}
						placeholder="Ej: MX"
						maxlength={2}
						disabled={loading}
					/>
					<p class="text-sm text-muted-foreground">Clave americana (hasta 2 caracteres)</p>
				</div>
			</div>

			<Dialog.Footer>
				<Button
					type="button"
					variant="outline"
					onclick={() => (open = false)}
					disabled={loading}
				>
					Cancelar
				</Button>
				<Button type="submit" disabled={loading}>
					{#if loading}
						<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
					{/if}
					{isEditing ? "Guardar cambios" : "Crear"}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
