<script lang="ts">
	import * as Card from "$lib/components/ui/card/index.js";
	import {
		FieldGroup,
		Field,
		FieldLabel,
		FieldDescription,
		FieldSeparator,
	} from "$lib/components/ui/field/index.js";
	import { Input } from "$lib/components/ui/input/index.js";
	import { Button } from "$lib/components/ui/button/index.js";
	import { cn } from "$lib/utils.js";
	import { FileText, ShieldCheck } from 'lucide-svelte';
	import type { HTMLAttributes } from "svelte/elements";
	import { page } from '$app/state';
	import { enhance } from '$app/forms';
	import { loginWithProvider } from '$lib/sso';
	import { onMount } from 'svelte';

	let { class: className, ...restProps }: HTMLAttributes<HTMLDivElement> = $props();

	const id = $props.id();
	
	let username = $state('demo');
	let password = $state('demo123');
	let tenantSlug = $state('aduanasoft');
	let loading = $state(false);
	
	// Obtener el error del servidor si existe
	const error = $derived(page.form?.error || '');
	
	// Limpiar todo el localStorage y cookies al montar el componente de login
	// Esto asegura que no queden datos del tenant anterior
	onMount(() => {
		clearAllData();
	});
	
	// Función para limpiar cookies del cliente
	function clearClientCookies() {
		if (typeof document !== 'undefined') {
			const isSecure = window.location.protocol === 'https:';
			const secureFlag = isSecure ? '; Secure' : '';
			document.cookie = `access_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; SameSite=Lax${secureFlag}`;
			document.cookie = `refresh_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; SameSite=Lax${secureFlag}`;
			document.cookie = `active_company_id=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; SameSite=Lax${secureFlag}`;
		}
	}
	
	// Función para limpiar todo el localStorage y cookies
	function clearAllData() {
		if (typeof localStorage !== 'undefined') {
			localStorage.removeItem('access_token');
			localStorage.removeItem('refresh_token');
			localStorage.removeItem('activeCompanyId');
		}
		
		clearClientCookies();
	}
	
	function handleMicrosoftLogin() {
		// Limpiar datos antes de iniciar SSO
		clearAllData();
		
		// Guardar el tenant_slug en localStorage para recuperarlo después del callback
		if (tenantSlug) {
			localStorage.setItem('pending_tenant_slug', tenantSlug);
		}
		loginWithProvider('microsoft');
	}
	
	function handleGoogleLogin() {
		// Limpiar datos antes de iniciar SSO
		clearAllData();
		
		// Guardar el tenant_slug en localStorage para recuperarlo después del callback
		if (tenantSlug) {
			localStorage.setItem('pending_tenant_slug', tenantSlug);
		}
		loginWithProvider('google');
	}
	
	function handleAppleLogin() {
		// Apple no está configurado por defecto en Keycloak, 
		// pero puedes agregarlo siguiendo el mismo patrón
		alert('Apple SSO no está configurado aún');
	}
</script>

<div class={cn("flex flex-col gap-6", className)} {...restProps}>
	<Card.Root class="overflow-hidden p-0">
		<Card.Content class="grid p-0 md:grid-cols-2">
			<form 
				class="p-6 md:p-8" 
				method="POST"
				use:enhance={() => {
					loading = true;
					return async ({ update, result }) => {
						await update();
						loading = false;
						
						// Si hay un error, limpiar cookies del cliente
						if (result.type === 'failure') {
							clearClientCookies();
						}
					};
				}}
			>
				<FieldGroup>
					<div class="flex flex-col items-center gap-2 text-center">
						<h1 class="text-2xl font-bold bg-gradient-to-r from-blue-600 to-blue-800 bg-clip-text text-transparent">Anexo 76</h1>
						<p class="text-muted-foreground text-balance text-sm">
							Sistema de Cumplimiento Fiscal y Aduanal
						</p>
					</div>
					
					{#if error}
						<div class="rounded-md bg-red-50 p-4 text-sm text-red-800">
							{error}
						</div>
					{/if}
					
					<Field>
						<FieldLabel for="tenant-{id}">Tenant</FieldLabel>
						<Input 
							id="tenant-{id}" 
							name="tenant_slug"
							type="text" 
							placeholder="aduanasoft" 
							bind:value={tenantSlug}
							required 
							disabled={loading}
						/>
					</Field>
					
					<Field>
						<FieldLabel for="username-{id}">Usuario</FieldLabel>
						<Input 
							id="username-{id}"
							name="username" 
							type="text" 
							placeholder="demo" 
							bind:value={username}
							required 
							disabled={loading}
						/>
					</Field>
					<Field>
						<div class="flex items-center">
							<FieldLabel for="password-{id}">Contraseña</FieldLabel>
							<a href="##" class="ml-auto text-sm underline-offset-2 hover:underline">
								¿Olvidaste tu contraseña?
							</a>
						</div>
						<Input 
							id="password-{id}"
							name="password" 
							type="password" 
							bind:value={password}
							required 
							disabled={loading}
						/>
					</Field>
					<Field>
						<Button type="submit" disabled={loading}>
							{loading ? 'Iniciando sesión...' : 'Iniciar sesión'}
						</Button>
					</Field>
					<FieldSeparator class="*:data-[slot=field-separator-content]:bg-card">
						O continua con
					</FieldSeparator>
					<Field class="grid grid-cols-3 gap-4">
						<Button variant="outline" type="button" onclick={handleAppleLogin} disabled={loading}>
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
								<path
									d="M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701"
									fill="currentColor"
								/>
							</svg>
							<span class="sr-only">Login with Apple</span>
						</Button>
						<Button variant="outline" type="button" onclick={handleGoogleLogin} disabled={loading}>
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
								<path
									d="M12.48 10.92v3.28h7.84c-.24 1.84-.853 3.187-1.787 4.133-1.147 1.147-2.933 2.4-6.053 2.4-4.827 0-8.6-3.893-8.6-8.72s3.773-8.72 8.6-8.72c2.6 0 4.507 1.027 5.907 2.347l2.307-2.307C18.747 1.44 16.133 0 12.48 0 5.867 0 .307 5.387.307 12s5.56 12 12.173 12c3.573 0 6.267-1.173 8.373-3.36 2.16-2.16 2.84-5.213 2.84-7.667 0-.76-.053-1.467-.173-2.053H12.48z"
									fill="currentColor"
								/>
							</svg>
							<span class="sr-only">Login with Google</span>
						</Button>
						<Button variant="outline" type="button" onclick={handleMicrosoftLogin} disabled={loading}>
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
								<path d="M11.4 24H0V12.6h11.4V24zM24 24H12.6V12.6H24V24zM11.4 11.4H0V0h11.4v11.4zm12.6 0H12.6V0H24v11.4z" fill="currentColor"/>
							</svg>
							<span class="sr-only">Login with Microsoft</span>
						</Button>
					</Field>
					<FieldDescription class="text-center">
						¿No tienes una cuenta? <a href="/register">Regístrate</a>
					</FieldDescription>
				</FieldGroup>
			</form>
			<div class="relative hidden md:block bg-gradient-to-br from-blue-50 to-slate-100 dark:from-slate-900 dark:to-blue-950">
				<div class="absolute inset-0 flex items-center justify-center p-12">
					<div class="relative w-full h-full flex flex-col items-center justify-center gap-8">
						<!-- Ícono principal - Escudo con documento -->
						<div class="relative">
							<FileText class="w-48 h-48 text-blue-600 dark:text-blue-400 opacity-90" strokeWidth={1.5} />
							<!-- Escudo de protección superpuesto -->
							<div class="absolute -bottom-2 -right-2 bg-white dark:bg-slate-800 rounded-full p-2 shadow-lg">
								<ShieldCheck class="w-12 h-12 text-green-600 dark:text-green-400" fill="currentColor" />
							</div>
						</div>
						
						<!-- Texto descriptivo -->
						<div class="text-center space-y-3 max-w-sm">
							<h2 class="text-2xl font-bold text-slate-800 dark:text-slate-100">
								Cumplimiento Simplificado
							</h2>
							<p class="text-slate-600 dark:text-slate-300 text-sm leading-relaxed">
								Gestiona tus obligaciones fiscales del Anexo 76 del SAT de manera eficiente y segura
							</p>
						</div>
						
						<!-- Elementos decorativos -->
						<div class="absolute top-8 left-8 w-20 h-20 border-2 border-blue-200 dark:border-blue-800 rounded-full opacity-50"></div>
						<div class="absolute bottom-8 right-8 w-16 h-16 border-2 border-blue-300 dark:border-blue-700 rounded-lg opacity-50 rotate-45"></div>
					</div>
				</div>
			</div>
		</Card.Content>
	</Card.Root>
	<FieldDescription class="px-6 text-center text-xs">
		Al continuar, aceptas nuestros <a href="##" class="underline hover:text-blue-600">Términos de Servicio</a> y
		<a href="##" class="underline hover:text-blue-600">Política de Privacidad</a>.
	</FieldDescription>
</div>
