"use client";

import Link from "next/link";
import { signIn } from "next-auth/react";
import { useState } from "react";

export default function RegisterPage() {
  const [error, setError] = useState<string | null>(null);
  const [done, setDone] = useState(false);

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

    const formData = new FormData(event.currentTarget);
    const payload = {
      name: formData.get("name"),
      email: formData.get("email"),
      password: formData.get("password")
    };

    const response = await fetch("/api/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload)
    });

    if (!response.ok) {
      const data = await response.json();
      setError(data.error || "Registrierung fehlgeschlagen.");
      return;
    }

    setDone(true);
    await signIn("credentials", {
      email: payload.email,
      password: payload.password,
      callbackUrl: "/"
    });
  };

  return (
    <div className="mx-auto max-w-md rounded bg-white p-6 shadow-sm">
      <h1 className="text-2xl font-semibold">Registrieren</h1>
      <form onSubmit={onSubmit} className="mt-4 space-y-3">
        <input
          name="name"
          type="text"
          placeholder="Name"
          className="w-full rounded border border-slate-300 px-3 py-2"
        />
        <input
          name="email"
          type="email"
          placeholder="E-Mail"
          required
          className="w-full rounded border border-slate-300 px-3 py-2"
        />
        <input
          name="password"
          type="password"
          placeholder="Passwort"
          required
          className="w-full rounded border border-slate-300 px-3 py-2"
        />
        <button type="submit" className="w-full rounded bg-brand-500 px-4 py-2 text-white">
          Konto anlegen
        </button>
      </form>
      {done && <p className="mt-3 text-sm text-emerald-600">Account erstellt.</p>}
      {error && <p className="mt-3 text-sm text-red-600">{error}</p>}
      <p className="mt-4 text-sm text-slate-600">
        Schon registriert? <Link href="/login" className="text-brand-700">Login</Link>
      </p>
    </div>
  );
}
