"use client";

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

export function ResetPasswordForm({ token }: { token: string | null }) {
  const router = useRouter();
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (!token) return;
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/account/reset-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, password }),
      });
      const data = await res.json();
      if (!data.ok) {
        setError(data.reason || "Passwort konnte nicht zurückgesetzt werden.");
        setLoading(false);
        return;
      }
      router.push("/konto/bestellungen");
      router.refresh();
    } catch {
      setError("Passwort konnte gerade nicht zurückgesetzt werden.");
      setLoading(false);
    }
  }

  if (!token) {
    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)" }}>
          Link ungültig
        </p>
        <p className="text-body text-text-muted">
          Dieser Link zum Zurücksetzen des Passworts ist ungültig oder abgelaufen. Fordere gerne einen neuen an.
        </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)" }}>
        Neues Passwort vergeben
      </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">Neues Passwort</span>
          <input
            type="password"
            required
            minLength={8}
            autoComplete="new-password"
            value={password}
            onChange={(e) => setPassword(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>
        {error && <p className="text-label text-red-600">{error}</p>}
        <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…" : "Passwort speichern"}
        </button>
      </form>
    </Reveal>
  );
}
