"use client";

import { useSearchParams } from "next/navigation";
import { useState } from "react";

export default function ResetConfirmClient() {
  const searchParams = useSearchParams();
  const token = searchParams.get("token");
  const [status, setStatus] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setStatus(null);
    setError(null);

    const formData = new FormData(event.currentTarget);
    const newPassword = formData.get("newPassword");

    const response = await fetch("/api/password-reset/confirm", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ token, newPassword })
    });

    if (!response.ok) {
      const data = await response.json();
      setError(data.error || "Passwort konnte nicht geändert werden.");
      return;
    }

    setStatus("Passwort aktualisiert. Du kannst dich jetzt anmelden.");
    event.currentTarget.reset();
  };

  if (!token) {
    return (
      <div className="mx-auto max-w-md card fade-up">
        <h1 className="text-2xl font-semibold">Ungültiger Link</h1>
        <p className="mt-1 text-sm text-slate-600">
          Der Link ist unvollständig oder abgelaufen.
        </p>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-md card fade-up">
      <h1 className="text-2xl font-semibold">Neues Passwort</h1>
      <p className="mt-1 text-sm text-slate-600">
        Setze ein neues Passwort für dein Konto.
      </p>
      <form onSubmit={onSubmit} className="mt-4 space-y-3">
        <input
          name="newPassword"
          type="password"
          placeholder="Neues Passwort"
          required
          className="w-full rounded-xl border border-slate-300 px-3 py-2"
        />
        <button type="submit" className="btn-accent w-full">
          Passwort speichern
        </button>
      </form>
      {status && <p className="mt-3 text-sm text-emerald-600">{status}</p>}
      {error && <p className="mt-3 text-sm text-red-600">{error}</p>}
    </div>
  );
}
