<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 { sectorsApi, type Sector, type CreateSectorData, type UpdateSectorData } from "$lib/api/dashboard/reference_data/sectors";
	import { companyStore } from '$lib/stores/company.svelte';

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

	let formData = $state({
		key: "",
		description: "",
		authorized: false
	});

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

	function getActiveCompanyId(): number | null {
		const fromStore = companyStore.activeCompany?.id;
		if (fromStore) return fromStore;
		if (typeof document === 'undefined') return null;
		const cookie = document.cookie
			.split('; ')
			.find((row) => row.startsWith('active_company_id='))
			?.split('=')[1];
		if (!cookie) return null;
		const parsed = Number(cookie);
		return Number.isFinite(parsed) ? parsed : null;
	}

	// Actualizar formData cuando item cambia
	$effect(() => {
		if (item) {
			formData = {
				key: item.key,
				description: item.description,
				authorized: item.authorized
			};
		} else {
			formData = {
				key: "",
				description: "",
				authorized: false
			};
		}
	});

	const isEditing = $derived(!!item);

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

		const companyId = getActiveCompanyId();
		if (!companyId) {
			error = 'No hay empresa activa seleccionada';
			loading = false;
			return;
		}

		try {
			let response;
			if (isEditing && item) {
				const payload: UpdateSectorData = {
					key: formData.key,
					description: formData.description,
					authorized: formData.authorized
				};
				response = await sectorsApi.update(item.id, payload, companyId);
			} else {
				const payload: CreateSectorData = {
					key: formData.key,
					description: formData.description,
					authorized: formData.authorized
				};
				response = await sectorsApi.create(payload, companyId);
			}

			if (response.error) {
				// Si es error de autenticación y ya se intentó refrescar, el API lo manejará
				// pero mostramos un mensaje más claro
				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) {
			formData = {
				key: "",
				description: "",
				authorized: false
			};
			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"} Sector
			</Dialog.Title>
			<Dialog.Description>
				{isEditing 
					? "Modifica los datos del sector."
					: "Completa los datos para crear un nuevo sector."}
			</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="space-y-2">
				<Label for="key">Clave *</Label>
				<Input
					id="key"
					bind:value={formData.key}
					placeholder="Ej: 01"
					maxlength={8}
					required
					disabled={loading || isEditing}
				/>
				<p class="text-sm text-muted-foreground">Clave de hasta 8 caracteres</p>
			</div>

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

			<div class="space-y-2">
				<Label>Autorizado *</Label>
				<div class="flex gap-4">
					<label class="flex items-center gap-2 cursor-pointer">
						<input
							type="radio"
							name="authorized"
							value="true"
							checked={formData.authorized === true}
							onchange={() => (formData.authorized = true)}
							disabled={loading}
							class="h-4 w-4 border-gray-300 text-primary focus:ring-primary"
						/>
						<span class="text-sm">Sí</span>
					</label>
					<label class="flex items-center gap-2 cursor-pointer">
						<input
							type="radio"
							name="authorized"
							value="false"
							checked={formData.authorized === false}
							onchange={() => (formData.authorized = false)}
							disabled={loading}
							class="h-4 w-4 border-gray-300 text-primary focus:ring-primary"
						/>
						<span class="text-sm">No</span>
					</label>
				</div>
			</div>

			<Dialog.Footer>
				<Button
					type="button"
					variant="outline"
					onclick={() => (open = false)}
					disabled={loading}
				>
					Cancelar
				</Button>
				<Button type="submit" disabled={loading}>
					{#if loading}
						<svg
							class="mr-2 h-4 w-4 animate-spin"
							xmlns="http://www.w3.org/2000/svg"
							fill="none"
							viewBox="0 0 24 24"
						>
							<circle
								class="opacity-25"
								cx="12"
								cy="12"
								r="10"
								stroke="currentColor"
								stroke-width="4"
							></circle>
							<path
								class="opacity-75"
								fill="currentColor"
								d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
							></path>
						</svg>
					{/if}
					{isEditing ? "Guardar cambios" : "Crear"}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
