"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { FormEvent, useEffect, useState } from "react";
import { ADMIN_API } from "@/lib/constants";

function formatLockoutRemaining(totalSec: number): string {
  if (totalSec < 60) return `${totalSec} s`;
  const m = Math.floor(totalSec / 60);
  const s = totalSec % 60;
  if (s === 0) return `${m} min`;
  return `${m} min ${s} s`;
}

export default function AdminLoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  /** Compte à rebours anti force brute (secondes restantes), null si pas bloqué. */
  const [lockoutRemainingSec, setLockoutRemainingSec] = useState<number | null>(
    null
  );

  useEffect(() => {
    fetch(`${ADMIN_API}/auth/me`, { credentials: "include" })
      .then((r) => r.json())
      .then((d) => {
        if (d.user) router.replace("/admin");
      })
      .catch(() => {});
  }, [router]);

  useEffect(() => {
    if (lockoutRemainingSec == null || lockoutRemainingSec <= 0) return;
    const t = setTimeout(() => {
      setLockoutRemainingSec((r) =>
        r != null && r > 1 ? r - 1 : null
      );
    }, 1000);
    return () => clearTimeout(t);
  }, [lockoutRemainingSec]);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const res = await fetch(`${ADMIN_API}/auth/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        if (res.status === 429) {
          const fromBody =
            typeof data.retryAfterSec === "number" &&
            Number.isFinite(data.retryAfterSec)
              ? Math.max(0, Math.ceil(data.retryAfterSec))
              : null;
          const headerRaw = res.headers.get("Retry-After");
          const fromHeader = headerRaw
            ? Math.max(0, parseInt(headerRaw, 10))
            : NaN;
          const sec =
            fromBody ??
            (Number.isFinite(fromHeader) ? fromHeader : null);
          if (sec != null && sec > 0) {
            setLockoutRemainingSec(sec);
            setError(null);
          } else {
            setLockoutRemainingSec(null);
            setError(
              typeof data.error === "string"
                ? data.error
                : "Trop de tentatives. Réessayez plus tard."
            );
          }
        } else {
          setLockoutRemainingSec(null);
          setError(
            typeof data.error === "string"
              ? data.error
              : "Connexion impossible"
          );
        }
        return;
      }
      setLockoutRemainingSec(null);
      window.location.href = "/admin";
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex min-h-screen flex-col items-center justify-center bg-cream px-4 py-12">
      <div className="w-full max-w-md rounded-[2rem] border border-chocolat/10 bg-white p-8 shadow-[0_20px_50px_-15px_rgba(61,43,31,0.2)]">
        <h1 className="text-center text-2xl font-bold text-chocolat">
          Administration
        </h1>
        <p className="mt-2 text-center text-sm text-muted">
          Connexion réservée au gérant
        </p>
        <form onSubmit={onSubmit} className="mt-8 flex flex-col gap-4">
          <label className="flex flex-col gap-1.5 text-sm font-medium text-chocolat">
            Email
            <input
              type="email"
              autoComplete="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              className="rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-3 text-foreground outline-none ring-gaufre/40 focus:ring-2"
            />
          </label>
          <label className="flex flex-col gap-1.5 text-sm font-medium text-chocolat">
            Mot de passe
            <span className="relative">
              <input
                type={showPassword ? "text" : "password"}
                autoComplete="current-password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                className="w-full rounded-2xl border border-chocolat/15 bg-cream/50 py-3 pl-4 pr-12 text-foreground outline-none ring-gaufre/40 focus:ring-2"
              />
              <button
                type="button"
                onClick={() => setShowPassword((v) => !v)}
                className="absolute right-3 top-1/2 -translate-y-1/2 rounded-lg p-1 text-chocolat/50 transition hover:text-chocolat"
                aria-label={
                  showPassword
                    ? "Masquer le mot de passe"
                    : "Afficher le mot de passe"
                }
              >
                {showPassword ? (
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="h-5 w-5"
                    aria-hidden
                  >
                    <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94" />
                    <path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19" />
                    <line x1="1" y1="1" x2="23" y2="23" />
                  </svg>
                ) : (
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="h-5 w-5"
                    aria-hidden
                  >
                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
                    <circle cx="12" cy="12" r="3" />
                  </svg>
                )}
              </button>
            </span>
          </label>
          {lockoutRemainingSec != null && lockoutRemainingSec > 0 && (
            <div
              className="rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-950"
              role="status"
            >
              <p className="font-semibold">Connexion temporairement bloquée</p>
              <p className="mt-1 text-amber-900/90">
                Trop de tentatives infructueuses. Temps restant avant un nouvel
                essai :{" "}
                <span className="font-mono font-semibold tabular-nums">
                  {formatLockoutRemaining(lockoutRemainingSec)}
                </span>
              </p>
            </div>
          )}
          {error && (
            <p className="rounded-2xl bg-red-50 px-3 py-2 text-sm text-red-700">
              {error}
            </p>
          )}
          <button
            type="submit"
            disabled={
              loading ||
              (lockoutRemainingSec != null && lockoutRemainingSec > 0)
            }
            className="mt-2 rounded-full bg-gaufre py-3.5 text-base font-semibold text-chocolat shadow-lg shadow-chocolat/15 transition hover:brightness-105 disabled:opacity-60"
          >
            {loading ? "Connexion…" : "Se connecter"}
          </button>
        </form>
        <p className="mt-6 text-center text-xs text-muted">
          <Link href="/" className="underline hover:text-chocolat">
            Retour au site
          </Link>
        </p>
      </div>
    </div>
  );
}
