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

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

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

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

		// Validar que las contraseñas coincidan
		if (formData.password !== formData.confirmPassword) {
			passwordError = 'Las contraseñas no coinciden';
			return;
		}

		// Validar longitud de contraseña
		if (formData.password.length < 8) {
			passwordError = 'La contraseña debe tener al menos 8 caracteres';
			return;
		}

		loading = true;

		try {
			const response = await api.auth.register({
				username: formData.username,
				email: formData.email,
				password: formData.password,
				first_name: formData.first_name,
				last_name: formData.last_name,
				tenant_slug: formData.tenant_slug
			});

			if (response.error) {
				throw new Error(response.error);
			}
			
			// Registro exitoso, redirigir al login
			alert(`¡Registro exitoso! Bienvenido ${response.data.username}`);
			goto('/login');
		} 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>

		<!-- 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}>
					<!-- Username -->
					<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"
							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"
						/>
					</div>

					<!-- 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
							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="usuario@ejemplo.com"
						/>
					</div>

					<!-- Nombre -->
					<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>

					<!-- Tenant -->
					<div>
						<label for="tenant_slug" class="block text-sm font-medium text-gray-700">
							Empresa
						</label>
						<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>
							<!-- Agregar más tenants aquí -->
						</select>
					</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 ? 'Registrando...' : '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>
	</div>
</div>
