"use client";

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

export default function RegisterPage() {
  const [error, setError] = useState<string | null>(null);
  const [showVerifyLink, setShowVerifyLink] = 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);
    setShowVerifyLink(false);

    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;
    }

    const emailValue = String(payload.email || "").trim().toLowerCase();
    const nextUrl = emailValue
      ? `/login?registered=1&email=${encodeURIComponent(emailValue)}`
      : "/login?registered=1";
    window.location.href = nextUrl;
  };

  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>
          {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>
      {showVerifyLink && (
        <p className="mt-2 text-sm text-slate-600">
          E-Mail nicht bestätigt?{" "}
          <Link href="/verify" className="text-brand-700">
            Link erneut senden
          </Link>
        </p>
      )}
    </div>
  );
}
