<script lang="ts">
  import { goto } from '$app/navigation';
  import Icon from '$lib/components/Icon.svelte';
  import { auth } from '$lib/stores/auth.js';
  import { toast } from '$lib/stores/toast.js';
  import { onMount } from 'svelte';

  let email = '';
  let password = '';
  let totpCode = '';
  let isLoading = false;
  let showTwoFactor = false;
  let errorMessage = '';

  onMount(() => {
    // Redirect if already authenticated
    if ($auth.isAuthenticated) {
      goto('/');
    }
  });

  async function handleLogin() {
    if (!email || !password) {
      errorMessage = 'Por favor completa todos los campos';
      return;
    }

    isLoading = true;
    errorMessage = '';

    try {
      await auth.login({
        email,
        password,
        tenant_slug: 'aduanasoft',
        totp_code: totpCode || undefined
      });

      toast.success('¡Bienvenido! Has iniciado sesión correctamente');
      goto('/');
    } catch (error: any) {
      console.error('Login error:', error);

      // Check if 2FA is required
      if (error.message.includes('two-factor') || error.message.includes('2FA')) {
        showTwoFactor = true;
        errorMessage = 'Introduce el código de tu aplicación de autenticación';
      } else {
        errorMessage = error.message || 'Error al iniciar sesión';
        toast.error(errorMessage);
      }
    } finally {
      isLoading = false;
    }
  }

  function handleKeyDown(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      handleLogin();
    }
  }
</script>

<svelte:head>
  <title>Acceso Admin - ServiceManager</title>
</svelte:head>

<div
  class="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-950 p-4 font-sans"
>
  <div
    class="w-full max-w-5xl grid grid-cols-1 md:grid-cols-2 bg-white dark:bg-gray-900 rounded-lg shadow-xl overflow-hidden border border-gray-200 dark:border-gray-800"
  >
    <!-- Left Side: Internal Branding -->
    <div
      class="hidden md:flex flex-col justify-between p-12 bg-gray-900 text-white relative overflow-hidden"
    >
      <!-- Grid pattern overlay -->
      <div
        class="absolute inset-0 opacity-10"
        style="background-image: radial-gradient(white 1px, transparent 1px); background-size: 30px 30px;"
      />

      <div class="relative z-10">
        <div class="flex items-center space-x-3 mb-6">
          <div class="p-2 bg-blue-500/20 rounded border border-blue-500/30">
            <Icon name="server" className="w-6 h-6 text-blue-400" />
          </div>
          <span class="text-sm font-mono tracking-wider text-blue-400">INTERNAL_ACCESS_V2</span>
        </div>

        <h1 class="text-3xl font-bold tracking-tight mb-4">Panel de Administración</h1>
        <p class="text-gray-400 text-sm leading-relaxed max-w-sm">
          Plataforma de gestión de servicios, monitoreo de tickets y administración de usuarios.
          Acceso restringido únicamente a personal autorizado.
        </p>
      </div>

      <div class="relative z-10 mt-12">
        <div class="space-y-3">
          <div class="flex items-center space-x-3 text-xs text-gray-400 font-mono">
            <Icon name="check-circle" className="w-4 h-4 text-green-500" />
            <span>System Status: Operational</span>
          </div>
          <div class="flex items-center space-x-3 text-xs text-gray-400 font-mono">
            <Icon name="shield" className="w-4 h-4 text-blue-500" />
            <span>256-bit Encryption Enabled</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Right Side: Login Form -->
    <div class="p-8 md:p-12 flex flex-col justify-center">
      <div class="max-w-sm mx-auto w-full">
        <div class="mb-8">
          <h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-1">Iniciar Sesión</h2>
          <p class="text-sm text-gray-500 dark:text-gray-400">Acceso al sistema central</p>
        </div>

        <form on:submit|preventDefault={handleLogin} class="space-y-5">
          {#if errorMessage}
            <div
              class="p-3 rounded-md bg-red-50 dark:bg-red-900/10 border border-red-200 dark:border-red-900 flex items-start gap-3"
            >
              <Icon
                name="alert-triangle"
                className="w-5 h-5 text-red-600 dark:text-red-500 flex-shrink-0 mt-0.5"
              />
              <p class="text-sm text-red-600 dark:text-red-500">{errorMessage}</p>
            </div>
          {/if}

          {#if !showTwoFactor}
            <div class="space-y-4">
              <div>
                <label
                  for="email"
                  class="block text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 mb-1"
                  >Usuario / Correo</label
                >
                <div class="relative group">
                  <div
                    class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400 group-focus-within:text-blue-500 transition-colors"
                  >
                    <Icon name="user" className="w-5 h-5" />
                  </div>
                  <input
                    id="email"
                    type="email"
                    bind:value={email}
                    on:keydown={handleKeyDown}
                    class="form-input w-full pl-10 py-2.5 bg-gray-50 dark:bg-gray-800 border-gray-300 dark:border-gray-700 rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all font-mono text-sm"
                    placeholder="admin@aduanasoft.com"
                    required
                    disabled={isLoading}
                  />
                </div>
              </div>

              <div>
                <label
                  for="password"
                  class="block text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 mb-1"
                  >Clave de Acceso</label
                >
                <div class="relative group">
                  <div
                    class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400 group-focus-within:text-blue-500 transition-colors"
                  >
                    <Icon name="lock" className="w-5 h-5" />
                  </div>
                  <input
                    id="password"
                    type="password"
                    bind:value={password}
                    on:keydown={handleKeyDown}
                    class="form-input w-full pl-10 py-2.5 bg-gray-50 dark:bg-gray-800 border-gray-300 dark:border-gray-700 rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all font-mono text-sm"
                    placeholder="••••••••••••"
                    required
                    disabled={isLoading}
                  />
                </div>
              </div>
            </div>
          {:else}
            <!-- 2FA Input -->
            <div
              class="bg-blue-50 dark:bg-blue-900/10 p-4 rounded-lg border border-blue-100 dark:border-blue-800/30"
            >
              <label
                for="code"
                class="block text-xs font-semibold uppercase tracking-wider text-blue-800 dark:text-blue-300 mb-2 text-center"
                >Verificación de Seguridad</label
              >
              <div class="relative">
                <input
                  id="code"
                  type="text"
                  bind:value={totpCode}
                  on:keydown={handleKeyDown}
                  class="form-input w-full py-3 rounded border-blue-300 dark:border-blue-700 focus:ring-blue-500 focus:border-blue-500 text-center tracking-[0.5em] font-mono text-lg bg-white dark:bg-gray-800"
                  placeholder="000000"
                  maxlength="6"
                  required
                  disabled={isLoading}
                  autofocus
                />
              </div>
              <p class="text-xs text-blue-600 dark:text-blue-400 mt-2 text-center">
                Consulte su dispositivo autenticador
              </p>
            </div>
          {/if}

          <div class="pt-4">
            <button
              type="submit"
              class="w-full flex justify-center py-2.5 px-4 rounded bg-gray-900 dark:bg-gray-700 text-white font-medium hover:bg-gray-800 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors disabled:opacity-50 disabled:cursor-not-allowed shadow-sm"
              disabled={isLoading}
            >
              {#if isLoading}
                <Icon name="loader" className="w-4 h-4 animate-spin mr-2" />
                Autenticando...
              {:else}
                {showTwoFactor ? 'Verificar Token' : 'Entrar al Panel'}
              {/if}
            </button>
          </div>
        </form>
      </div>

      <div class="mt-8 pt-6 border-t border-gray-100 dark:border-gray-800">
        <p class="text-[10px] text-gray-400 text-center uppercase tracking-widest">
          Aduanasoft Internal Systems © 2024
        </p>
      </div>
    </div>
  </div>
</div>
