<script>
  import { goto } from '$app/navigation';
  import { auth } from '$lib/stores/auth.js';
  import { login } from '$lib/api/auth.js';
  import { onMount } from 'svelte';
  import { User, Lock, Eye, EyeOff, LogIn } from 'lucide-svelte';

  let username = '';
  let password = '';
  let error = '';
  let loading = false;
  let showPassword = false;
  let rememberMe = false;
  let usernameError = '';
  let passwordError = '';

  onMount(() => {
    const savedUsername = localStorage.getItem('clqms_username');
    const savedRemember = localStorage.getItem('clqms_remember') === 'true';
    
    if (savedRemember && savedUsername) {
      username = savedUsername;
      rememberMe = true;
    }
  });

  function togglePassword() {
    showPassword = !showPassword;
  }

  function validateForm() {
    let isValid = true;
    
    usernameError = '';
    passwordError = '';
    
    if (!username.trim()) {
      usernameError = 'Username is required';
      isValid = false;
    } else if (username.length < 3) {
      usernameError = 'Username must be at least 3 characters';
      isValid = false;
    }
    /*
    if (!password) {
      passwordError = 'Password is required';
      isValid = false;
    } else if (password.length < 6) {
      passwordError = 'Password must be at least 6 characters';
      isValid = false;
    }
    */
    return isValid;
  }

  async function handleSubmit() {
    error = '';
    
    if (!validateForm()) return;
    
    loading = true;

    try {
      const response = await login(username, password);
      
      // Cookie is set by backend, now fetch user data
      const isAuthenticated = await auth.checkAuth();
      
      if (!isAuthenticated) {
        throw new Error('Failed to verify authentication');
      }
      
      if (rememberMe) {
        localStorage.setItem('clqms_username', username);
        localStorage.setItem('clqms_remember', 'true');
      } else {
        localStorage.removeItem('clqms_username');
        localStorage.setItem('clqms_remember', 'false');
      }
      
      await goto('/dashboard');
    } catch (err) {
      error = err.message || 'Login failed. Please try again.';
    } finally {
      loading = false;
    }
  }
</script>

<svelte:head>
  <title>CLQMS - Login</title>
</svelte:head>

<div class="hero min-h-screen bg-white">
  <div class="hero-content flex-col w-full max-w-lg">
    <!-- Logo Section -->
    <div class="text-center mb-4">
<div class="w-16 h-16 mx-auto rounded-xl bg-primary/10 flex items-center justify-center mb-3 shadow border-2 border-primary/20">
        <svg class="w-10 h-10 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"/>
        </svg>
      </div>
      <h1 class="text-3xl font-bold text-primary mb-1">CLQMS</h1>
      <p class="text-gray-600 text-sm">Clinical Laboratory Quality Management System</p>
    </div>

    <!-- Login Card -->
    <div class="card bg-white w-full max-w-md shadow-xl border border-gray-200 border-t-4 border-t-secondary">
      <div class="card-body p-6">
        <h2 class="text-xl font-bold text-center text-secondary mb-4">Welcome Back</h2>
        
        <form on:submit|preventDefault={handleSubmit}>
          <!-- Username Field -->
          <div class="mb-3">
<label class="input w-full input-sm input-bordered bg-white border-gray-300 flex items-center gap-2 {usernameError ? 'border-red-500' : ''}">
              <span class="label"><User class="w-4 h-4 text-secondary" /></span>
              <input 
                type="text" 
                id="username" 
                name="username" 
                placeholder="Username" 
                autocomplete="username"
                bind:value={username}
                disabled={loading}
                class="grow text-gray-900 placeholder-gray-400"
              />
            </label>
            {#if usernameError}
              <p class="text-red-500 text-sm mt-1">{usernameError}</p>
            {/if}
          </div>

          <!-- Password Field -->
          <div class="mb-3">
<label class="input w-full input-sm input-bordered bg-white border-gray-300 flex items-center gap-2 {passwordError ? 'border-red-500' : ''}">
              <span class="label"><Lock class="w-4 h-4 text-secondary" /></span>
              <input 
                type={showPassword ? 'text' : 'password'} 
                id="password" 
                name="password" 
                placeholder="Password" 
                autocomplete="current-password"
                bind:value={password}
                disabled={loading}
                class="grow text-gray-900 placeholder-gray-400"
              />
              <button type="button" class="btn btn-ghost btn-xs btn-circle" on:click={togglePassword} disabled={loading}>
                {#if showPassword}
                  <EyeOff class="w-4 h-4 text-secondary" />
                {:else}
                  <Eye class="w-4 h-4 text-secondary" />
                {/if}
              </button>
            </label>
            {#if passwordError}
              <p class="text-red-500 text-sm mt-1">{passwordError}</p>
            {/if}
          </div>

          <!-- Remember Me & Forgot Password -->
          <div class="flex items-center justify-between mb-4">
<label class="label cursor-pointer flex items-center gap-2">
              <input type="checkbox" bind:checked={rememberMe} class="checkbox checkbox-sm checkbox-secondary" disabled={loading} />
              <span class="label-text text-sm">Remember me</span>
            </label>
            <a href="#" class="text-sm text-secondary hover:underline">Forgot password?</a>
          </div>

          <!-- Error Message -->
          {#if error}
            <div class="alert alert-error text-sm mb-4">
              <span>{error}</span>
            </div>
          {/if}

          <!-- Login Button -->
          <div class="form-control">
            <button type="submit" class="btn btn-sm btn-primary text-white shadow hover:shadow-lg transition-all w-full" disabled={loading}>
              {#if loading}
                <span class="loading loading-spinner loading-xs mr-2"></span>
                Signing in...
              {:else}
                <LogIn class="w-4 h-4 mr-2" />
                Sign In
              {/if}
            </button>
          </div>
        </form>

        <!-- Divider -->
        <div class="divider text-sm text-gray-400">or</div>

        <!-- Help Text -->
        <p class="text-center text-sm text-gray-500">
          Need help? Contact your system administrator
        </p>
      </div>
    </div>

    <!-- Footer -->
    <div class="mt-6 text-center">
      <p class="text-xs text-gray-400">© 2026 CLQMS. All rights reserved.</p>
    </div>
  </div>
</div>
