"use client";

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

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

  useEffect(() => {
    const loadRegistration = async () => {
      try {
        const response = await fetch("/api/settings/registration");
        if (!response.ok) return;
        const payload = await response.json();
        setRegistrationEnabled(payload.registrationEnabled !== false);
      } catch {
        setRegistrationEnabled(true);
      }
    };
    loadRegistration();
  }, []);

  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 card fade-up">
      <h1 className="text-2xl font-semibold">Registrieren</h1>
      {registrationEnabled === false ? (
        <div className="mt-4 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-700">
          Registrierung ist derzeit deaktiviert.
        </div>
      ) : registrationEnabled === null ? (
        <p className="mt-4 text-sm text-slate-600">
          Registrierung wird geladen...
        </p>
      ) : (
        <>
          <form onSubmit={onSubmit} className="mt-4 space-y-3">
            <input
              name="name"
              type="text"
              placeholder="Name"
              className="w-full rounded-xl border border-slate-300 px-3 py-2"
            />
            <input
              name="email"
              type="email"
              placeholder="E-Mail"
              required
              className="w-full rounded-xl border border-slate-300 px-3 py-2"
            />
            <input
              name="password"
              type="password"
              placeholder="Passwort"
              required
              className="w-full rounded-xl border border-slate-300 px-3 py-2"
            />
            <button type="submit" className="btn-accent w-full">
              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>
  );
}
