<script>
  import { goto } from '$app/navigation';
  import { auth } from '$lib/stores/auth.js';
  import { login } from '$lib/api/auth.js';
  import { onMount } from '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);
      auth.login(response.token, response.user);
      
      if (rememberMe) {
        localStorage.setItem('clqms_username', username);
        localStorage.setItem('clqms_remember', 'true');
      } else {
        localStorage.removeItem('clqms_username');
        localStorage.setItem('clqms_remember', 'false');
      }
      
      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-6">
      <div class="w-20 h-20 mx-auto rounded-2xl bg-emerald-100 flex items-center justify-center mb-4 shadow-lg border-2 border-emerald-200">
        <svg class="w-12 h-12 text-emerald-600" 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-4xl font-bold text-emerald-600 mb-2">CLQMS</h1>
      <p class="text-gray-600">Clinical Laboratory Quality Management System</p>
    </div>

    <!-- Login Card -->
    <div class="card bg-white w-full max-w-xl shadow-2xl border border-gray-200 border-t-4 border-t-emerald-500">
      <div class="card-body p-8">
        <h2 class="text-2xl font-bold text-center text-emerald-700 mb-6">Welcome Back</h2>
        
        <form on:submit|preventDefault={handleSubmit}>
          <!-- Username Field -->
          <div class="mb-4">
            <label class="input w-full input-bordered bg-white border-gray-300 flex items-center gap-2 {usernameError ? 'border-red-500' : ''}">
              <span class="label"><i class="fa-solid fa-user text-emerald-500"></i></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-4">
            <label class="input w-full input-bordered bg-white border-gray-300 flex items-center gap-2 {passwordError ? 'border-red-500' : ''}">
              <span class="label"><i class="fa-solid fa-lock text-emerald-500"></i></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-sm btn-circle" on:click={togglePassword} disabled={loading}>
                <i class="fa-solid {showPassword ? 'fa-eye-slash' : 'fa-eye'} text-emerald-500"></i>
              </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-6">
            <label class="label cursor-pointer flex items-center gap-2">
              <input type="checkbox" bind:checked={rememberMe} class="checkbox checkbox-sm checkbox-emerald" disabled={loading} />
              <span class="label-text text-sm">Remember me</span>
            </label>
            <a href="#" class="text-sm text-emerald-600 hover:text-emerald-700 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 bg-emerald-600 hover:bg-emerald-700 text-white shadow-lg hover:shadow-xl transition-all w-full" disabled={loading}>
              {#if loading}
                <span class="loading loading-spinner loading-sm mr-2"></span>
                Signing in...
              {:else}
                <i class="fa-solid fa-right-to-bracket mr-2"></i>
                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-8 text-center">
      <p class="text-sm text-gray-400">© 2026 CLQMS. All rights reserved.</p>
    </div>
  </div>
</div>
