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

  let user: { email?: string; username?: string } | null = $state(null);
  let oldPassword = $state('');
  let newPassword = $state('');
  let confirmPassword = $state('');
  let error = $state('');
  let success = $state(false);
  let loading = $state(false);

  onMount(async () => {
    const token = localStorage.getItem('token');
    if (!token) {
      await goto('/auth/login');
      return;
    }

    try {
      const res = await fetch('/api/auth/me', {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      if (!res.ok) {
        await goto('/auth/login');
        return;
      }

      const data = await res.json();
      user = data.data;
    } catch {
      await goto('/auth/login');
    }
  });

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

    if (newPassword !== confirmPassword) {
      error = 'Passwords do not match';
      return;
    }

    if (newPassword.length < 8) {
      error = 'Password must be at least 8 characters';
      return;
    }

    loading = true;

    try {
      const res = await fetch('/api/auth/change-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${localStorage.getItem('token')}`,
        },
        body: JSON.stringify({ oldPassword, newPassword }),
      });

      const data = await res.json();

      if (!res.ok) {
        error = data.error || 'Failed to change password';
        return;
      }

      success = true;
      oldPassword = '';
      newPassword = '';
      confirmPassword = '';
    } catch (err) {
      error = 'Connection error';
    } finally {
      loading = false;
    }
  }

  function handleLogout() {
    localStorage.removeItem('token');
    goto('/auth/login');
  }
</script>

<div class="page-container">
  <header class="header">
    <div class="header-content">
      <h1>Change Password</h1>
      <div class="user-info">
        {#if user}
          <span>Logged in as <strong>{user.email || user.username}</strong></span>
        {/if}
        <button class="logout" onclick={handleLogout}>Logout</button>
      </div>
    </div>
  </header>

  <div class="content">
    {#if error}
      <div class="error">{error}</div>
    {/if}

    {#if success}
      <div class="success">
        Password changed successfully!
      </div>
    {/if}

    <form onsubmit={handleSubmit}>
      <label>
        Current Password
        <input 
          type="password" 
          bind:value={oldPassword} 
          placeholder="Enter current password"
          required 
          disabled={loading}
        />
      </label>

      <label>
        New Password
        <input 
          type="password" 
          bind:value={newPassword} 
          placeholder="Enter new password (min 8 characters)"
          required 
          disabled={loading}
        />
      </label>

      <label>
        Confirm New Password
        <input 
          type="password" 
          bind:value={confirmPassword} 
          placeholder="Confirm new password"
          required 
          disabled={loading}
        />
      </label>

      <button type="submit" disabled={loading}>
        {loading ? 'Changing...' : 'Change Password'}
      </button>
    </form>

    <div class="links">
      <a href="/auth/dashboard">Back to Dashboard</a>
    </div>
  </div>
</div>

<style>
  .page-container {
    min-height: 100vh;
    background: #f5f7fa;
  }

  .header {
    background: white;
    padding: 1rem 2rem;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }

  .header-content {
    max-width: 800px;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .header h1 {
    margin: 0;
    font-size: 1.5rem;
    color: #2c3e50;
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 1rem;
  }

  .logout {
    padding: 0.5rem 1rem;
    background: #e74c3c;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }

  .content {
    max-width: 500px;
    margin: 2rem auto;
    padding: 2rem;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }

  .error {
    background: #fee;
    color: #c00;
    padding: 0.75rem;
    border-radius: 4px;
    margin-bottom: 1rem;
  }

  .success {
    background: #efe;
    color: #060;
    padding: 0.75rem;
    border-radius: 4px;
    margin-bottom: 1rem;
  }

  form {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  label {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    font-weight: 500;
    color: #555;
  }

  input {
    padding: 0.75rem;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 1rem;
  }

  input:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  }

  button {
    padding: 0.75rem;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 1rem;
    font-weight: 500;
    cursor: pointer;
    margin-top: 0.5rem;
  }

  button:hover:not(:disabled) {
    opacity: 0.9;
  }

  button:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }

  .links {
    margin-top: 1.5rem;
    text-align: center;
  }

  .links a {
    color: #667eea;
    text-decoration: none;
  }

  .links a:hover {
    text-decoration: underline;
  }
</style>
