"use client";

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

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

  const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError(null);
    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: true,
      callbackUrl: "/"
    });

    if (result?.error) {
      setError("Login fehlgeschlagen.");
    }
  };

  return (
    <div className="mx-auto max-w-md rounded bg-white p-6 shadow-sm">
      <h1 className="text-2xl font-semibold">Login</h1>
      <form onSubmit={onSubmit} className="mt-4 space-y-3">
        <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">
          Anmelden
        </button>
      </form>
      {error && <p className="mt-3 text-sm text-red-600">{error}</p>}
      <p className="mt-4 text-sm text-slate-600">
        Kein Konto? <Link href="/register" className="text-brand-700">Registrieren</Link>
      </p>
    </div>
  );
}
