"use client";

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

export function LoginForm() {
  const [mode, setMode] = useState<"login" | "register">("login");
  const [message, setMessage] = useState("");

  async function submit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    const email = String(data.get("email"));
    const password = String(data.get("password"));
    const name = String(data.get("name") || "");

    if (mode === "register") {
      const response = await fetch("/api/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password, name })
      });
      if (!response.ok) {
        setMessage("Registration failed.");
        return;
      }
    }

    await signIn("credentials", { email, password, redirectTo: "/dashboard" });
  }

  return (
    <div className="mt-6">
      <div className="grid grid-cols-2 rounded-lg border border-white/10 p-1">
        <button className={`rounded-md py-2 text-sm font-semibold ${mode === "login" ? "bg-cyanx text-ink" : "text-white/62"}`} onClick={() => setMode("login")} type="button">Login</button>
        <button className={`rounded-md py-2 text-sm font-semibold ${mode === "register" ? "bg-cyanx text-ink" : "text-white/62"}`} onClick={() => setMode("register")} type="button">Register</button>
      </div>
      <button onClick={() => signIn("google", { redirectTo: "/dashboard" })} className="mt-5 w-full rounded-lg border border-white/12 px-4 py-3 text-sm font-semibold text-white hover:border-cyanx" type="button">
        Continue with Google
      </button>
      <form onSubmit={submit} className="mt-5 space-y-3">
        {mode === "register" && <input name="name" className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white outline-none focus:border-cyanx" placeholder="Name" />}
        <input name="email" type="email" required className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white outline-none focus:border-cyanx" placeholder="Email" />
        <input name="password" type="password" required minLength={8} className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white outline-none focus:border-cyanx" placeholder="Password" />
        <button className="w-full rounded-lg bg-cyanx px-4 py-3 text-sm font-black text-ink">{mode === "login" ? "Login" : "Create account"}</button>
      </form>
      <button onClick={() => signIn("nodemailer", { email: prompt("Email address"), redirectTo: "/dashboard" })} className="mt-3 w-full text-sm text-cyanx" type="button">
        Email me a magic login link
      </button>
      {message && <p className="mt-3 text-sm text-red-300">{message}</p>}
    </div>
  );
}
