"use client";

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

export default function LoginPage() {
  const router = useRouter();
  const [mode, setMode] = useState<"login" | "register">("login");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    console.log("[login] submit fired, mode:", mode);
    setError("");
    setLoading(true);

    try {
      if (mode === "register") {
        if (!name.trim()) {
          setError("Name required");
          setLoading(false);
          return;
        }
        console.log("[login] POST /api/auth/register");
        const res = await fetch("/api/auth/register", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ name, email, password }),
        });
        console.log("[login] register status", res.status);

        if (!res.ok) {
          const data = await res.json().catch(() => ({}));
          setError(data.error || `Registration failed (${res.status})`);
          setLoading(false);
          return;
        }
      }

      console.log("[login] calling signIn");
      const result = await signIn("credentials", {
        email,
        password,
        redirect: false,
      });
      console.log("[login] signIn result:", result);

      if (!result || result.error) {
        setError(mode === "register" ? "Account created but sign-in failed. Try logging in." : "Invalid email or password");
        setLoading(false);
        return;
      }

      setLoading(false);
      router.push("/");
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong");
      setLoading(false);
    }
  }

  return (
    <div className="flex items-center justify-center min-h-screen">
      <div className="w-full max-w-sm p-8 bg-surface border border-gold/20 rounded-2xl shadow-lg">
        <h1 className="text-2xl font-bold text-gold text-center mb-6">
          {mode === "login" ? "Welcome Back" : "Create Account"}
        </h1>

        <form onSubmit={handleSubmit} className="flex flex-col gap-4">
          {mode === "register" && (
            <input
              type="text"
              placeholder="Name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="px-4 py-3 bg-bg border border-gold/10 rounded-xl text-ink placeholder-dim focus:outline-none focus:border-gold/40 transition-colors"
            />
          )}
          <input
            type="email"
            placeholder="Email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            className="px-4 py-3 bg-bg border border-gold/10 rounded-xl text-ink placeholder-dim focus:outline-none focus:border-gold/40 transition-colors"
          />
          <input
            type="password"
            placeholder="Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            className="px-4 py-3 bg-bg border border-gold/10 rounded-xl text-ink placeholder-dim focus:outline-none focus:border-gold/40 transition-colors"
          />

          {error && (
            <p className="text-rust text-sm text-center">{error}</p>
          )}

          <button
            type="submit"
            disabled={loading}
            className="w-full py-3 bg-gradient-to-br from-gold to-amber-600 hover:from-gold-glow hover:to-gold text-bg font-semibold rounded-xl shadow-md hover:shadow-lg hover:shadow-gold/30 transition-all duration-300 active:scale-95 disabled:opacity-50"
          >
            {loading ? "..." : mode === "login" ? "Login" : "Register"}
          </button>
        </form>

        <p className="text-dim text-sm text-center mt-6">
          {mode === "login" ? "Don't have an account?" : "Already have an account?"}{" "}
          <button
            type="button"
            onClick={() => { setMode(mode === "login" ? "register" : "login"); setError(""); }}
            className="text-gold hover:text-gold-glow transition-colors cursor-pointer"
          >
            {mode === "login" ? "Register" : "Login"}
          </button>
        </p>
      </div>
    </div>
  );
}
