"use client";

import { useState } from "react";
import { Reveal } from "../../../components/Reveal";

const inputClass =
  "w-full border border-border rounded-sm px-4 py-3 text-body-sm text-text-primary outline-none focus:border-brand transition-colors";

export function PasswordForm({ email }: { email: string }) {
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [saving, setSaving] = useState(false);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const formEl = e.currentTarget;
    setSaving(true);
    setError(null);
    setSuccess(false);

    const form = new FormData(formEl);
    const currentPassword = String(form.get("currentPassword") ?? "");
    const newPassword = String(form.get("newPassword") ?? "");

    try {
      const res = await fetch("/api/account/password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ currentPassword, newPassword }),
      });
      const data = await res.json();
      if (!data.ok) {
        setError(data.reason || "Passwort konnte nicht geändert werden.");
        setSaving(false);
        return;
      }
      setSuccess(true);
      setSaving(false);
      formEl.reset();
    } catch {
      setError("Passwort konnte gerade nicht geändert werden.");
      setSaving(false);
    }
  }

  return (
    <Reveal className="flex flex-col gap-6 items-start w-full pt-4 border-t border-border">
      <p className="font-semibold text-h-small text-text-primary" style={{ fontFamily: "var(--font-lora)" }}>
        Passwort ändern
      </p>
      <form onSubmit={handleSubmit} className="flex flex-col gap-4 items-start w-full">
        {/* Hidden, but present so autofill/password managers correctly
            associate the new password with this account's email. */}
        <input type="hidden" name="email" value={email} autoComplete="username" />
        <label className="flex flex-col gap-2 items-start w-full sm:w-1/2">
          <span className="text-label text-text-muted">Aktuelles Passwort</span>
          <input type="password" name="currentPassword" autoComplete="current-password" required className={inputClass} />
        </label>
        <label className="flex flex-col gap-2 items-start w-full sm:w-1/2">
          <span className="text-label text-text-muted">Neues Passwort</span>
          <input type="password" name="newPassword" autoComplete="new-password" minLength={8} required className={inputClass} />
        </label>

        {error && <p className="text-label text-red-600">{error}</p>}
        {success && <p className="text-label text-success">Passwort geändert.</p>}

        <button
          type="submit"
          disabled={saving}
          className={`px-7 py-3 rounded-sm bg-brand hover:bg-brand-hover font-bold text-body-sm text-text-primary transition-colors ${saving ? "opacity-70 pointer-events-none" : ""}`}
        >
          {saving ? "Speichert…" : "Passwort ändern"}
        </button>
      </form>
    </Reveal>
  );
}
