"use client";

import { appTitle } from "@/lib/public-env";
import { motion } from "framer-motion";
import { signIn } from "next-auth/react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";

export function LoginForm({ callbackUrl }: { callbackUrl: string }) {
  const router = useRouter();
  const registerHref = `/register?callbackUrl=${encodeURIComponent(callbackUrl)}`;
  const [emailOrUsername, setEmailOrUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setBusy(true);
    setError(null);
    const res = await signIn("credentials", {
      email: emailOrUsername.trim(),
      password,
      redirect: false,
      callbackUrl,
    });
    setBusy(false);
    if (res?.error) { setError("Invalid email/username or password."); return; }
    router.push(callbackUrl);
    router.refresh();
  };

  return (
    <div className="relative flex min-h-[80vh] flex-col items-center justify-center px-4 py-16">
      {/* Background glow */}
      <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_60%_50%_at_50%_30%,rgba(56,189,248,0.10),transparent)]" />

      <motion.div
        initial={{ opacity: 0, y: 24, scale: 0.97 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        transition={{ duration: 0.5 }}
        className="relative w-full max-w-md"
      >
        <div className="rounded-3xl border border-white/10 bg-white/[0.04] p-8 shadow-[0_0_80px_rgba(56,189,248,0.10)] backdrop-blur-xl">
          {/* Inner border shimmer */}
          <div className="pointer-events-none absolute inset-0 rounded-3xl border border-sky-400/10" />

          <p className="text-xs uppercase tracking-[0.28em] text-sky-300/80">Secure portal access</p>
          <h1 className="mt-2 text-3xl font-bold text-white">Sign in</h1>
          <p className="mt-1.5 text-sm text-slate-400">
            Supporter login for{" "}
            <span className="text-slate-300">{appTitle()}</span>
          </p>
          <p className="mt-3 rounded-xl border border-white/8 bg-white/[0.04] px-3 py-2 text-xs text-slate-400">
            Access is restricted to credentials issued by the committee. Unauthorized use may violate law or committee policy.
          </p>

          <form onSubmit={submit} className="mt-7 space-y-4">
            <div>
              <label className="block text-sm font-medium text-slate-300" htmlFor="login-id">
                Email or username
              </label>
              <input
                id="login-id"
                type="text"
                autoComplete="username"
                required
                value={emailOrUsername}
                onChange={(e) => setEmailOrUsername(e.target.value)}
                className="mt-2 w-full rounded-xl border border-white/10 bg-black/40 px-4 py-3 text-base text-white placeholder-slate-600 outline-none ring-sky-500/40 transition focus:border-sky-500/40 focus:ring"
                placeholder="you@example.com or supporter_name"
              />
            </div>

            <div>
              <div className="flex items-center justify-between">
                <label className="block text-sm font-medium text-slate-300" htmlFor="password">
                  Password
                </label>
                <Link href="/forgot-password" className="text-xs text-sky-400 hover:text-sky-300 transition">
                  Forgot password?
                </Link>
              </div>
              <input
                id="password"
                type="password"
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="mt-2 w-full rounded-xl border border-white/10 bg-black/40 px-4 py-3 text-base text-white placeholder-slate-600 outline-none ring-sky-500/40 transition focus:border-sky-500/40 focus:ring"
                placeholder="••••••••"
              />
            </div>

            {error ? (
              <motion.p
                initial={{ opacity: 0, y: -4 }}
                animate={{ opacity: 1, y: 0 }}
                className="rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-300"
              >
                {error}
              </motion.p>
            ) : null}

            <motion.button
              type="submit"
              disabled={busy}
              whileTap={{ scale: 0.98 }}
              className="group relative w-full overflow-hidden rounded-2xl bg-gradient-to-r from-sky-500 to-indigo-500 py-3.5 font-semibold text-white shadow-xl shadow-indigo-500/30 disabled:opacity-50"
            >
              <span className="relative z-10">{busy ? "Signing in…" : "Continue →"}</span>
              <span className="absolute inset-0 -translate-x-full bg-gradient-to-r from-transparent via-white/15 to-transparent transition-transform duration-500 group-hover:translate-x-full" />
            </motion.button>
          </form>

          <p className="mt-6 text-center text-sm text-slate-500">
            Need credentials?{" "}
            <Link className="font-medium text-sky-300 hover:text-sky-200 transition" href={registerHref}>
              Create an account
            </Link>
          </p>
        </div>
      </motion.div>
    </div>
  );
}
