"use client";

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

export function ForgotPasswordForm() {
  const [email, setEmail] = useState("");
  const [sent, setSent] = useState(false);
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);
    try {
      await fetch("/api/account/forgot-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
    } catch {
      // Same "always show success" reasoning as the route itself — a
      // network hiccup here shouldn't reveal anything either.
    }
    setSent(true);
    setLoading(false);
  }

  if (sent) {
    return (
      <Reveal className="flex flex-col gap-4 items-start pt-10 pb-20 px-[var(--layout-padding-x)] w-full max-w-[26rem] mx-auto">
        <p className="font-semibold text-h-feature text-text-primary" style={{ fontFamily: "var(--font-lora)" }}>
          E-Mail unterwegs
        </p>
        <p className="text-body text-text-muted">
          Falls zu <strong>{email}</strong> ein Konto existiert, haben wir dir eine E-Mail mit einem Link zum
          Zurücksetzen deines Passworts geschickt.
        </p>
      </Reveal>
    );
  }

  return (
    <Reveal className="flex flex-col gap-6 items-start pt-10 pb-20 px-[var(--layout-padding-x)] w-full max-w-[26rem] mx-auto">
      <p className="font-semibold text-h-feature text-text-primary" style={{ fontFamily: "var(--font-lora)" }}>
        Passwort vergessen
      </p>
      <p className="text-body text-text-muted">
        Gib deine E-Mail-Adresse ein — wir schicken dir einen Link, mit dem du ein neues Passwort vergeben kannst.
      </p>
      <form onSubmit={handleSubmit} className="flex flex-col gap-4 items-start w-full">
        <label className="flex flex-col gap-2 items-start w-full">
          <span className="text-label text-text-muted">E-Mail-Adresse</span>
          <input
            type="email"
            required
            autoComplete="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="w-full border border-border rounded-sm px-4 py-3 text-body-sm text-text-primary outline-none focus:border-brand transition-colors"
          />
        </label>
        <button
          type="submit"
          disabled={loading}
          className={`w-full flex items-center justify-center py-4 rounded-sm bg-brand hover:bg-brand-hover active:scale-[0.97] transition-all font-bold text-body text-text-primary ${loading ? "opacity-70 pointer-events-none" : ""}`}
        >
          {loading ? "Einen Moment…" : "Link anfordern"}
        </button>
      </form>
    </Reveal>
  );
}
