<script lang="ts">
	import { goto } from '$app/navigation';
	import { api } from '$lib/api';
	import { onMount } from 'svelte';

	// Parámetros del URL — se rellenan desde el link de invitación
	let inviteToken = $state('');
	let inviteTenantSlug = $state('');
	let inviteEmail = $state('');
	let isInviteFlow = $state(false);

	// Estado del check previo
	let checkLoading = $state(false);
	let checkDone = $state(false);
	let userExists = $state(false);
	let checkError = $state('');

	onMount(async () => {
		const params = new URL(window.location.href).searchParams;
		inviteToken = params.get('invite_token') ?? '';
		inviteTenantSlug = params.get('tenant') ?? '';
		inviteEmail = params.get('email') ?? '';
		isInviteFlow = Boolean(inviteToken && inviteTenantSlug);

		if (isInviteFlow) {
			formData.tenant_slug = inviteTenantSlug;
			if (inviteEmail) formData.email = inviteEmail;
			// Verificar si el usuario ya existe y validar el token
			await checkInvite();
		}
	});

	async function checkInvite() {
		checkLoading = true;
		checkError = '';
		try {
			const qs = new URLSearchParams({
				invite_token: inviteToken,
				tenant_slug: inviteTenantSlug,
				email: inviteEmail,
			});
			const resp = await api.get<{
				email: string;
				role: string;
				user_exists: boolean;
				username?: string;
				first_name?: string;
				last_name?: string;
			}>(`/v1/auth/register/check?${qs}`);

			if (resp.error) {
				checkError = resp.error || 'Token de invitación inválido o expirado';
				return;
			}
			const data = resp.data!;
			userExists = data.user_exists ?? false;
			if (data.first_name) formData.first_name = data.first_name;
			if (data.last_name) formData.last_name = data.last_name;
			if (data.username) formData.username = data.username;
			checkDone = true;
		} catch {
			checkError = 'No se pudo validar la invitación. Verifica el enlace.';
		} finally {
			checkLoading = false;
		}
	}

	let formData = $state({
		username: '',
		email: '',
		password: '',
		confirmPassword: '',
		first_name: '',
		last_name: '',
		tenant_slug: 'aduanasoft'
	});

	let loading = $state(false);
	let error = $state('');
	let passwordError = $state('');
	let success = $state(false);

	async function handleRegister(e: Event) {
		e.preventDefault();
		error = '';
		passwordError = '';

		if (!userExists) {
			if (formData.password !== formData.confirmPassword) {
				passwordError = 'Las contraseñas no coinciden';
				return;
			}
			if (formData.password.length < 8) {
				passwordError = 'La contraseña debe tener al menos 8 caracteres';
				return;
			}
		}

		loading = true;

		try {
			const payload: Record<string, string> = {
				username: formData.username,
				email: formData.email,
				password: formData.password || 'placeholder',
				first_name: formData.first_name,
				last_name: formData.last_name,
				tenant_slug: formData.tenant_slug,
			};

			if (inviteToken) {
				payload.invite_token = inviteToken;
			}

			const response = await api.auth.register(payload as any);

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

			success = true;
			setTimeout(() => {
				goto(`/login?tenant=${encodeURIComponent(formData.tenant_slug)}`);
			}, 3000);
		} catch (err: any) {
			error = err.message || 'Error al registrar usuario';
		} finally {
			loading = false;
		}
	}

	function handleCancel() {
		goto('/');
	}
</script>

<div class="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
	<div class="mx-auto max-w-md">
		<!-- Header -->
		<div class="text-center">
			<h2 class="text-3xl font-bold tracking-tight text-gray-900">Crear cuenta</h2>
			<p class="mt-2 text-sm text-gray-600">
				¿Ya tienes una cuenta?
				<a href="/login" class="font-medium text-blue-600 hover:text-blue-500">
					Inicia sesión
				</a>
			</p>
		</div>

		<!-- Banner de invitación -->
		{#if isInviteFlow}
			<div class="mt-4 rounded-md bg-blue-50 border border-blue-200 p-4">
				<div class="flex">
					<svg class="h-5 w-5 text-blue-400 mt-0.5 mr-3 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
						<path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
					</svg>
					<div>
						<p class="text-sm font-medium text-blue-800">Invitación válida</p>
						<p class="text-sm text-blue-700 mt-1">
							Estás registrándote en <strong>{inviteTenantSlug}</strong>.
							El enlace caduca en 48 horas y es de un solo uso.
						</p>
					</div>
				</div>
			</div>
		{/if}

		<!-- Verificando token -->
		{#if isInviteFlow && checkLoading}
			<div class="mt-8 rounded-lg bg-white px-6 py-8 shadow text-center">
				<p class="text-gray-600">Verificando invitación...</p>
			</div>

		<!-- Token inválido -->
		{:else if isInviteFlow && checkError}
			<div class="mt-8 rounded-lg bg-white px-6 py-8 shadow">
				<div class="rounded-md bg-red-50 p-4">
					<p class="text-sm font-medium text-red-800">Invitación inválida</p>
					<p class="text-sm text-red-700 mt-1">{checkError}</p>
				</div>
				<a href="/" class="mt-4 inline-block text-sm text-blue-600 hover:underline">
					Volver al inicio
				</a>
			</div>

		<!-- Pantalla de éxito -->
		{:else if success}
			<div class="mt-8 rounded-lg bg-white px-6 py-8 shadow text-center">
				<div class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-green-100">
					<svg class="h-6 w-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
						<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
					</svg>
				</div>
				<h3 class="text-lg font-semibold text-gray-900">¡Cuenta creada!</h3>
				<p class="mt-2 text-sm text-gray-600">
					{#if userExists}
						Tu cuenta ha sido vinculada a <strong>{inviteTenantSlug}</strong>.
					{:else}
						Te hemos enviado un correo de verificación a <strong>{formData.email}</strong>.
						Confirma tu email antes de iniciar sesión.
					{/if}
				</p>
				<p class="mt-1 text-xs text-gray-500">Redirigiendo al login...</p>
				<a
					href="/login"
					class="mt-6 inline-block rounded-md bg-blue-600 px-5 py-2 text-sm font-semibold text-white hover:bg-blue-500"
				>
					Ir al login
				</a>
			</div>

		<!-- Formulario (solo si token válido o no es flujo de invite) -->
		{:else if !isInviteFlow || (isInviteFlow && checkDone)}
		<!-- Formulario de registro -->
		<div class="mt-8">
			<div class="rounded-lg bg-white px-6 py-8 shadow">
				<form class="space-y-6" onsubmit={handleRegister}>

					<!-- Si ya existe: solo confirmar nombre -->
					{#if userExists}
						<div class="rounded-md bg-amber-50 border border-amber-200 p-4">
							<p class="text-sm text-amber-800">
								Ya tienes una cuenta en el sistema. Al confirmar quedarás vinculado a
								<strong>{inviteTenantSlug}</strong>.
							</p>
						</div>
					{/if}

					<!-- Username -->
					{#if !userExists}
					<div>
						<label for="username" class="block text-sm font-medium text-gray-700">
							Usuario
						</label>
						<input
							type="text"
							id="username"
							bind:value={formData.username}
							required
							minlength="3"
							maxlength="50"
							pattern="[a-z0-9.\-]+"
							title="Solo letras minúsculas, números, puntos o guiones"
							class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-blue-500"
							placeholder="usuario123"
						/>
						<p class="mt-1 text-xs text-gray-500">Solo letras minúsculas, números, puntos y guiones.</p>
					</div>
					{/if}

					<!-- Email -->
					<div>
						<label for="email" class="block text-sm font-medium text-gray-700">
							Email
						</label>
						<input
							type="email"
							id="email"
							bind:value={formData.email}
							required
							readonly={isInviteFlow && Boolean(inviteEmail)}
							class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-blue-500 {isInviteFlow && inviteEmail ? 'bg-gray-50 text-gray-500 cursor-not-allowed' : ''}"
							placeholder="usuario@ejemplo.com"
						/>
						{#if isInviteFlow && inviteEmail}
							<p class="mt-1 text-xs text-gray-500">El email está fijado por la invitación.</p>
						{/if}
					</div>

					<!-- Nombre y Apellido -->
					{#if !userExists}
					<div class="grid grid-cols-2 gap-4">
						<div>
							<label for="first_name" class="block text-sm font-medium text-gray-700">
								Nombre
							</label>
							<input
								type="text"
								id="first_name"
								bind:value={formData.first_name}
								required
								minlength="2"
								maxlength="50"
								class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-blue-500"
								placeholder="Juan"
							/>
						</div>
						<div>
							<label for="last_name" class="block text-sm font-medium text-gray-700">
								Apellido
							</label>
							<input
								type="text"
								id="last_name"
								bind:value={formData.last_name}
								required
								minlength="2"
								maxlength="50"
								class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-blue-500"
								placeholder="Pérez"
							/>
						</div>
					</div>

					<!-- Contraseña -->
					<div>
						<label for="password" class="block text-sm font-medium text-gray-700">
							Contraseña
						</label>
						<input
							type="password"
							id="password"
							bind:value={formData.password}
							required
							minlength="8"
							class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-blue-500"
							placeholder="Mínimo 8 caracteres"
						/>
					</div>

					<!-- Confirmar contraseña -->
					<div>
						<label for="confirmPassword" class="block text-sm font-medium text-gray-700">
							Confirmar contraseña
						</label>
						<input
							type="password"
							id="confirmPassword"
							bind:value={formData.confirmPassword}
							required
							minlength="8"
							class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-blue-500"
							placeholder="Repite tu contraseña"
						/>
						{#if passwordError}
							<p class="mt-1 text-sm text-red-600">{passwordError}</p>
						{/if}
					</div>
					{/if}

					<!-- Tenant -->
					<div>
						<label for="tenant_slug" class="block text-sm font-medium text-gray-700">
							Empresa
						</label>
						{#if isInviteFlow}
							<input
								type="text"
								id="tenant_slug"
								value={formData.tenant_slug}
								readonly
								class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm bg-gray-50 text-gray-500 cursor-not-allowed"
							/>
							<p class="mt-1 text-xs text-gray-500">Fijado por la invitación.</p>
						{:else}
							<select
								id="tenant_slug"
								bind:value={formData.tenant_slug}
								required
								class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-blue-500"
							>
								<option value="aduanasoft">AduanaSoft</option>
							</select>
						{/if}
					</div>

					<!-- Errores -->
					{#if error}
						<div class="rounded-md bg-red-50 p-4">
							<p class="text-sm text-red-800">{error}</p>
						</div>
					{/if}

					<!-- Botones -->
					<div class="flex gap-4">
						<button
							type="button"
							onclick={handleCancel}
							disabled={loading}
							class="flex-1 rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-semibold text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
						>
							Cancelar
						</button>
						<button
							type="submit"
							disabled={loading}
							class="flex-1 rounded-md bg-blue-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
						>
							{loading ? (userExists ? 'Vinculando...' : 'Registrando...') : (userExists ? 'Confirmar y unirme' : 'Registrarse')}
						</button>
					</div>
				</form>

				<!-- Info adicional -->
				<div class="mt-6 border-t border-gray-200 pt-6">
					<p class="text-xs text-gray-500">
						Al registrarte, aceptas nuestros términos de servicio y política de privacidad.
					</p>
				</div>
			</div>
		</div>
		{/if}
	</div>
</div>
