"use client";
import { signIn } from "next-auth/react";
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Captcha from "@/components/auth/Captcha";

export default function LoginForm({
  siteName,
  googleEnabled,
  captchaSiteKey,
  redirectTo = "/",
}: {
  siteName: string;
  googleEnabled: boolean;
  captchaSiteKey: string;
  redirectTo?: string;
}) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [captchaToken, setCaptchaToken] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    if (captchaSiteKey && !captchaToken) {
      setError("Please complete the captcha.");
      return;
    }
    setLoading(true);
    const res = await signIn("credentials", { email, password, captchaToken, redirect: false });
    setLoading(false);
    if (res?.error) setError("Invalid email or password.");
    else {
      router.push(redirectTo);
      router.refresh();
    }
  }

  const inputCls =
    "w-full bg-neutral-950 border border-neutral-800 rounded-lg px-3 py-2.5 text-sm outline-none focus:border-red-600";

  return (
    <div className="min-h-[80vh] flex items-center justify-center py-8">
      <div className="w-full max-w-4xl grid md:grid-cols-2 gap-6 items-stretch" style={{ transform: "scale(0.92)", transformOrigin: "center" }}>
        {/* Left welcome panel */}
        <div className="hidden md:flex flex-col justify-center rounded-2xl p-8 bg-gradient-to-br from-[#3d1220] to-[#140a0d] border border-[#4d1a28]">
          <span className="inline-flex items-center gap-2 self-center text-xs font-bold tracking-widest bg-black/40 border border-red-800 text-red-400 rounded-full px-4 py-1.5 mb-6">
            🔒 SIGN IN
          </span>
          <h1 className="text-3xl font-bold text-center">
            Welcome <span className="text-red-500">back</span>
          </h1>
          <p className="text-neutral-300 text-sm text-center mt-4">
            Sign in to continue to {siteName} and pick up where you left off.
          </p>
          <p className="text-neutral-500 text-xs text-center mt-4">
            Join our community to share prayer requests, encourage others with reactions and
            comments, and connect with fellow believers.
          </p>
          <div className="flex flex-wrap justify-center gap-4 mt-6 text-xs text-neutral-400">
            <span>🔒 Secure sign-in</span>
            <span>✓ Your data is safe</span>
            <span>✓ Sync across devices</span>
          </div>
        </div>

        {/* Right form card */}
        <div className="card p-6 md:p-8">
          <div className="flex items-center gap-3 mb-1">
            <div className="w-10 h-10 rounded-full bg-red-900/50 flex items-center justify-center text-red-400">👤</div>
            <div>
              <h2 className="font-bold">Sign in to your account</h2>
              <p className="text-xs text-neutral-500">Enter your email and password</p>
            </div>
          </div>

          {googleEnabled && (
            <>
              <button
                type="button"
                onClick={() => signIn("google", { callbackUrl: redirectTo })}
                className="w-full mt-5 bg-white text-black rounded-lg py-2.5 text-sm font-semibold flex items-center justify-center gap-2 hover:bg-neutral-200"
              >
                <span className="font-bold text-lg leading-none">G</span> Continue with Google
              </button>
              <div className="text-center text-xs text-neutral-500 my-4">or continue with email</div>
            </>
          )}

          <form onSubmit={handleSubmit} className="space-y-4 mt-4">
            <div>
              <label className="block text-xs font-semibold mb-1.5">Email address</label>
              <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} className={inputCls} />
            </div>
            <div>
              <label className="block text-xs font-semibold mb-1.5">Password</label>
              <input type="password" required value={password} onChange={(e) => setPassword(e.target.value)} className={inputCls} />
            </div>

            <Captcha siteKey={captchaSiteKey} onToken={setCaptchaToken} />

            {error && <p className="text-red-500 text-sm">{error}</p>}

            <button type="submit" disabled={loading} className="btn-primary w-full py-2.5">
              {loading ? "Signing in..." : "Sign in"}
            </button>
          </form>

          <p className="text-sm text-neutral-400 mt-5 text-center">
            Don&apos;t have an account? <Link href="/register" className="text-red-500 font-semibold">Sign up</Link>
          </p>
        </div>
      </div>
    </div>
  );
}
