"use client";

import { useRouter } from "next/navigation";
import { signIn } from "next-auth/react";
import { useCallback, useEffect, useRef, useState } from "react";
import AdminInput from "@/components/admin/AdminInput";
import AdminButton from "@/components/admin/AdminButton";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faEnvelope,
  faLock,
  faLockOpen,
  faShieldHalved,
  faTriangleExclamation,
} from "@fortawesome/free-solid-svg-icons";

/** After this many consecutive failed attempts, impose a cooldown. */
const MAX_ATTEMPTS_BEFORE_LOCKOUT = 3;
/** Lockout duration in seconds. */
const LOCKOUT_SECONDS = 30;

export default function AdminLoginPage() {
  const router = useRouter();
  const [callbackUrl, setCallbackUrl] = useState("/admin");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const failedAttempts = useRef(0);
  const [lockedUntil, setLockedUntil] = useState<number | null>(null);
  const [lockCountdown, setLockCountdown] = useState(0);

  useEffect(() => {
    try {
      const sp = new URLSearchParams(window.location.search);
      const cb = sp.get("callbackUrl");
      if (cb) setCallbackUrl(cb);
    } catch {
      // ignore
    }
  }, []);

  useEffect(() => {
    if (!lockedUntil) return;

    const tick = () => {
      const remaining = Math.ceil((lockedUntil - Date.now()) / 1000);
      if (remaining <= 0) {
        setLockedUntil(null);
        setLockCountdown(0);
      } else {
        setLockCountdown(remaining);
      }
    };

    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, [lockedUntil]);

  const isLocked = lockedUntil !== null && Date.now() < lockedUntil;

  const onSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();
      if (isLocked) return;

      setError(null);
      setLoading(true);
      try {
        const res = await signIn("credentials", {
          email,
          password,
          redirect: false,
          callbackUrl,
        });

        if (!res?.ok) {
          failedAttempts.current += 1;

          if (failedAttempts.current >= MAX_ATTEMPTS_BEFORE_LOCKOUT) {
            const until = Date.now() + LOCKOUT_SECONDS * 1000;
            setLockedUntil(until);
            setError(
              `Too many failed attempts. Please wait ${LOCKOUT_SECONDS} seconds before trying again.`,
            );
          } else {
            setError("Invalid email or password. Please try again.");
          }
          return;
        }

        failedAttempts.current = 0;
        router.push(res.url ?? callbackUrl);
      } catch (err) {
        setError("An error occurred. Please try again.");
      } finally {
        setLoading(false);
      }
    },
    [email, password, callbackUrl, isLocked, router],
  );

  return (
    <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-slate-950 px-4 py-12 text-slate-100">
      {/* Decorative background */}
      <div
        aria-hidden="true"
        className="pointer-events-none absolute inset-0"
        style={{
          background:
            "radial-gradient(600px circle at 20% 10%, rgba(99, 102, 241, 0.10), transparent 50%), radial-gradient(500px circle at 80% 90%, rgba(99, 102, 241, 0.06), transparent 50%)",
        }}
      />

      <div className="relative w-full max-w-md">
        <div className="rounded-2xl border border-slate-800 bg-slate-900/80 p-8 shadow-2xl shadow-black/40 backdrop-blur">
          <div className="mb-8 text-center">
            <div className="mb-4 inline-flex h-14 w-14 items-center justify-center rounded-xl bg-indigo-500/10 text-indigo-400 ring-1 ring-inset ring-indigo-500/20">
              <FontAwesomeIcon icon={faShieldHalved} className="h-6 w-6" />
            </div>
            <h1 className="text-2xl font-semibold tracking-tight text-slate-100">
              Admin Console
            </h1>
            <p className="mt-1 text-sm text-slate-400">
              Sign in to manage your site
            </p>
          </div>

          {error && (
            <div className="mb-5 flex items-start gap-2.5 rounded-lg border border-rose-500/30 bg-rose-500/10 p-3 text-sm text-rose-200">
              <FontAwesomeIcon
                icon={faTriangleExclamation}
                className="mt-0.5 h-4 w-4 shrink-0 text-rose-400"
              />
              <p>{error}</p>
            </div>
          )}

          {isLocked && lockCountdown > 0 && (
            <div className="mb-5 flex items-start gap-2.5 rounded-lg border border-amber-500/30 bg-amber-500/10 p-3 text-sm text-amber-200">
              <FontAwesomeIcon
                icon={faLock}
                className="mt-0.5 h-4 w-4 shrink-0 text-amber-400"
              />
              <p>
                Account temporarily locked. Try again in{" "}
                <span className="font-semibold">{lockCountdown}s</span>.
              </p>
            </div>
          )}

          <form onSubmit={onSubmit} className="space-y-4">
            <AdminInput
              id="admin-login-email"
              label="Email address"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              autoComplete="username"
              required
              placeholder="you@example.com"
              leftIcon={<FontAwesomeIcon icon={faEnvelope} className="h-3.5 w-3.5" />}
            />

            <AdminInput
              id="admin-login-password"
              label="Password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              autoComplete="current-password"
              required
              placeholder="••••••••"
              leftIcon={<FontAwesomeIcon icon={faLock} className="h-3.5 w-3.5" />}
            />

            <AdminButton
              type="submit"
              variant="primary"
              isLoading={loading}
              disabled={isLocked}
              className="w-full"
              size="lg"
              icon={!loading && !isLocked ? faLockOpen : undefined}
            >
              {loading
                ? "Signing in..."
                : isLocked
                  ? `Locked (${lockCountdown}s)`
                  : "Sign in"}
            </AdminButton>
          </form>
        </div>

        <p className="mt-6 text-center text-xs text-slate-500">
          Authorized personnel only. All access is logged.
        </p>
      </div>
    </div>
  );
}
