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

  let user: { 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;
    }

    const payload = decodeJWT(token);
    if (payload) {
      user = { username: payload.username };
    }
  });

  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="min-h-screen bg-base-200" data-theme="light">
  <header class="bg-base-100 shadow">
    <div class="max-w-2xl mx-auto px-6 py-4 flex justify-between items-center">
      <h1 class="text-xl font-bold">Change Password</h1>
      <div class="flex items-center gap-4">
        {#if user}
          <span class="text-base-content/60">Logged in as <strong>{user.username}</strong></span>
        {/if}
        <button class="btn btn-error btn-sm" onclick={handleLogout}>Logout</button>
      </div>
    </div>
  </header>

  <main class="max-w-md mx-auto mt-8 p-6">
    <div class="card bg-base-100 shadow">
      <div class="card-body">
        {#if error}
          <div class="alert alert-error mb-4">
            <span>{error}</span>
          </div>
        {/if}

        {#if success}
          <div class="alert alert-success mb-4">
            <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span>Password changed successfully!</span>
          </div>
        {/if}

        <form onsubmit={handleSubmit} class="space-y-4">
          <fieldset class="fieldset">
            <legend class="fieldset-legend">Current Password</legend>
            <input
              type="password"
              class="input input-bordered w-full"
              bind:value={oldPassword}
              placeholder="Enter current password"
              required
              disabled={loading}
            />
          </fieldset>

          <fieldset class="fieldset">
            <legend class="fieldset-legend">New Password</legend>
            <input
              type="password"
              class="input input-bordered w-full"
              bind:value={newPassword}
              placeholder="Enter new password (min 8 characters)"
              required
              disabled={loading}
            />
          </fieldset>

          <fieldset class="fieldset">
            <legend class="fieldset-legend">Confirm New Password</legend>
            <input
              type="password"
              class="input input-bordered w-full"
              bind:value={confirmPassword}
              placeholder="Confirm new password"
              required
              disabled={loading}
            />
          </fieldset>

          <button type="submit" class="btn btn-primary w-full" disabled={loading}>
            {#if loading}
              <span class="loading loading-spinner loading-sm"></span>
              Changing...
            {:else}
              Change Password
            {/if}
          </button>
        </form>

        <div class="text-center mt-4">
          <a href="/" class="link link-primary">Back to Dashboard</a>
        </div>
      </div>
    </div>
  </main>
</div>
