"use client";

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

export default function LoginPage() {
  const router = useRouter();
  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 email = formData.get("email") as string;
    const password = formData.get("password") as string;

    const result = await signIn("credentials", {
      email,
      password,
      redirect: false
    });

    if (result?.error) {
      if (result.error === "PENDING") {
        setError("Dein Konto wartet auf Freischaltung durch einen Admin.");
        return;
      }
      if (result.error === "EMAIL_NOT_VERIFIED") {
        setError("Bitte bestätige zuerst deine E-Mail.");
        setShowVerifyLink(true);
        return;
      }
      if (result.error === "LOCKED") {
        setError("Zu viele Versuche. Bitte später erneut versuchen.");
        return;
      }
      if (result.error === "RATE_LIMIT") {
        setError("Zu viele Anfragen. Bitte später erneut versuchen.");
        return;
      }
      setError("Login fehlgeschlagen.");
      return;
    }

    if (result?.ok) {
      setShowVerifyLink(false);
      router.push("/");
    }
  };

  return (
    <div className="mx-auto max-w-md card fade-up">
      <h1 className="text-2xl font-semibold">Login</h1>
      <p className="mt-1 text-sm text-slate-600">
        Bitte anmelden.
      </p>
      <form onSubmit={onSubmit} className="mt-4 space-y-3">
        <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">
          Anmelden
        </button>
      </form>
      {error && <p className="mt-3 text-sm text-red-600">{error}</p>}
      {registrationEnabled !== false && (
        <p className="mt-4 text-sm text-slate-600">
          Kein Konto?{" "}
          <Link href="/register" className="text-brand-700">
            Registrieren
          </Link>
        </p>
      )}
      <p className="mt-2 text-sm text-slate-600">
        Passwort vergessen?{" "}
        <Link href="/reset" className="text-brand-700">
          Zurücksetzen
        </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>
  );
}
