"use client"

import Image from "next/image"
import { useMemo } from "react"
import { useSearchParams } from "next/navigation"
import { useLocale, useTranslations } from "next-intl"
import { ShieldCheck, AlertCircle, Lock, Zap, BarChart3 } from "lucide-react"

import { LoginForm } from "@/src/features/auth/login-form"
import { useAuthGuard } from "@/src/features/auth/use-auth-guard"
import { FullPageLoader } from "@/src/components/app/FullPageLoader"
import { LocaleSwitcher } from "@/src/components/LocaleSwitcher"

type Reason = "revoked" | "expired" | null

// ── Palette extraite du logo ACX ──────────────────────────────────────────
const C = {
  navy:      "#1a3578",   // bleu marine profond (lettres ACX)
  navyMid:   "#1e4494",   // marine intermédiaire
  navyLight: "#2655b0",   // marine clair
  teal:      "#4dba96",   // vert teal (silhouette + arc)
  tealLight: "#6ecdb0",   // teal clair
  tealPale:  "#d0f0e6",   // teal très pâle (accents sur fond blanc)
}

export default function LoginPage() {
  const t = useTranslations("auth")
  const locale = useLocale()
  const searchParams = useSearchParams()

  const { checking } = useAuthGuard({
    mode: "redirectIfAuth",
    redirectTo: `/${locale}/dashboard`,
  })

  const reason: Reason = useMemo(() => {
    const r = searchParams.get("reason")
    if (r === "revoked" || r === "expired") return r
    return null
  }, [searchParams])

  if (checking) return <FullPageLoader />

  const stats = [
    { value: t("stat1Value"), label: t("stat1Label"), icon: Zap },
    { value: t("stat2Value"), label: t("stat2Label"), icon: BarChart3 },
    { value: t("stat3Value"), label: t("stat3Label"), icon: Lock },
  ]

  return (
    <main className="h-[100dvh] w-full overflow-hidden lg:grid lg:grid-cols-2">

      {/* ── PANNEAU GAUCHE — branding marine ─────────────────────────────── */}
      <section
        className="relative hidden lg:flex flex-col h-full overflow-hidden select-none"
        style={{
          background: `linear-gradient(155deg, ${C.navy} 0%, ${C.navyMid} 50%, ${C.navyLight} 100%)`,
        }}
      >
        {/* Halo teal en haut à droite */}
        <div className="pointer-events-none absolute inset-0 overflow-hidden">
          <div
            className="absolute -top-28 -right-28 h-[520px] w-[520px] rounded-full opacity-[0.22]"
            style={{ background: `radial-gradient(circle, ${C.teal}, transparent 65%)` }}
          />
          {/* Halo teal clair en bas à gauche */}
          <div
            className="absolute -bottom-40 -left-20 h-[400px] w-[400px] rounded-full opacity-[0.12]"
            style={{ background: `radial-gradient(circle, ${C.tealLight}, transparent 70%)` }}
          />
          {/* Grille de points blancs */}
          <svg className="absolute inset-0 h-full w-full opacity-[0.06]" xmlns="http://www.w3.org/2000/svg">
            <defs>
              <pattern id="grid-dots" x="0" y="0" width="28" height="28" patternUnits="userSpaceOnUse">
                <circle cx="2" cy="2" r="1.5" fill="white" />
              </pattern>
            </defs>
            <rect width="100%" height="100%" fill="url(#grid-dots)" />
          </svg>
          {/* Diagonales très subtiles */}
          <div
            className="absolute inset-0 opacity-[0.03]"
            style={{
              background:
                "repeating-linear-gradient(-45deg, white, white 1px, transparent 1px, transparent 42px)",
            }}
          />
        </div>

        <div className="relative flex h-full flex-col px-12 py-10">

          {/* Top bar */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2.5">
              <div
                className="flex h-8 w-8 items-center justify-center rounded-xl ring-1"
                style={{
                  background: `rgba(77,186,150,0.20)`,
                  borderColor: `rgba(77,186,150,0.30)`,
                }}
              >
                <ShieldCheck className="h-4 w-4" style={{ color: C.tealLight }} />
              </div>
              <span className="text-sm font-medium text-white/85">{t("badge")}</span>
            </div>
            <div className="[&_select]:border-white/20 [&_select]:bg-white/10 [&_select]:text-white [&_select]:text-sm [&_option]:text-slate-900">
              <LocaleSwitcher />
            </div>
          </div>

          {/* Contenu central */}
          <div className="flex flex-1 flex-col justify-center">

            {/* Pastille live */}
            <div
              className="mb-8 inline-flex w-fit items-center gap-2 rounded-full px-3.5 py-1.5 ring-1"
              style={{
                background: `rgba(77,186,150,0.12)`,
                borderColor: `rgba(77,186,150,0.28)`,
              }}
            >
              <span className="relative flex h-2 w-2">
                <span
                  className="absolute inline-flex h-full w-full animate-ping rounded-full opacity-75"
                  style={{ backgroundColor: C.tealLight }}
                />
                <span
                  className="relative inline-flex h-2 w-2 rounded-full"
                  style={{ backgroundColor: C.teal }}
                />
              </span>
              <span className="text-xs font-medium" style={{ color: C.tealLight }}>
                ACX Collections
              </span>
            </div>

            {/* Titre */}
            <h1 className="max-w-sm text-[2.6rem] font-bold leading-[1.08] tracking-tight text-white">
              {t("heroTitle")}
            </h1>
            <p className="mt-5 max-w-sm text-[15px] leading-relaxed text-white/55">
              {t("heroSubtitle")}
            </p>

            {/* Stats */}
            <div className="mt-12 grid grid-cols-3 gap-3">
              {stats.map(({ value, label, icon: Icon }) => (
                <div
                  key={label}
                  className="flex flex-col items-start gap-2 rounded-2xl px-4 py-4 ring-1"
                  style={{
                    background: "rgba(255,255,255,0.06)",
                    borderColor: "rgba(255,255,255,0.10)",
                  }}
                >
                  <Icon className="h-4 w-4" style={{ color: C.teal, opacity: 0.7 }} />
                  <div>
                    <p className="text-lg font-bold leading-none text-white">{value}</p>
                    <p className="mt-1 text-[11px] uppercase tracking-wider text-white/40">{label}</p>
                  </div>
                </div>
              ))}
            </div>

            {/* Note sécurité */}
            <div
              className="mt-10 flex items-center gap-3 rounded-2xl px-4 py-3 ring-1"
              style={{
                background: "rgba(255,255,255,0.04)",
                borderColor: "rgba(255,255,255,0.08)",
              }}
            >
              <Lock className="h-4 w-4 shrink-0 text-white/35" />
              <p className="text-xs leading-relaxed text-white/35">{t("footerNote")}</p>
            </div>
          </div>

          {/* Filigrane bas */}
          <div className="flex items-center gap-3">
            <div className="h-px flex-1 bg-white/10" />
            <span className="text-[11px] text-white/30 tracking-widest uppercase">Acremac</span>
            <div className="h-px flex-1 bg-white/10" />
          </div>
        </div>
      </section>

      {/* ── PANNEAU DROIT — formulaire ───────────────────────────────────── */}
      <section className="flex h-full flex-col overflow-y-auto" style={{ background: "#f7f8fc" }}>
        <div className="flex flex-1 flex-col items-center justify-center px-8 py-16 sm:px-12">
          <div className="w-full max-w-[380px]">

            {/* Mobile top bar */}
            <div className="mb-10 flex items-center justify-between lg:hidden">
              <div className="flex items-center gap-2">
                <ShieldCheck className="h-4 w-4" style={{ color: C.teal }} />
                <span className="text-sm font-medium text-slate-700">{t("badge")}</span>
              </div>
              <LocaleSwitcher />
            </div>

            {/* Logo */}
            <div className="mb-10">
              <div
                className="overflow-hidden rounded-3xl bg-white shadow-md ring-1"
                style={{ width: 180, height: 68, borderColor: "rgba(26,53,120,0.08)" }}
              >
                <Image
                  src="/logo-acx.png"
                  alt="ACX — Acremac Claims XMultigestion"
                  width={180}
                  height={68}
                  priority
                  className="h-full w-full object-contain p-2"
                />
              </div>
            </div>

            {/* Headline */}
            <div className="mb-10">
              <h2
                className="text-[1.85rem] font-bold tracking-tight"
                style={{ color: C.navy }}
              >
                {t("title")}
              </h2>
              <p className="mt-2 text-[15px] text-slate-500">{t("subtitle")}</p>
            </div>

            {/* Bannière session */}
            {reason && (
              <div
                className="mb-7 flex items-start gap-3 rounded-2xl border px-4 py-3.5 text-sm"
                style={{
                  borderColor: "rgba(185,28,28,0.18)",
                  background: "rgba(254,242,242,0.9)",
                  color: "#991b1b",
                }}
              >
                <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
                <div>
                  <p className="font-semibold">
                    {reason === "revoked" ? t("session_revoked_title") : t("session_expired_title")}
                  </p>
                  <p className="mt-0.5 text-xs leading-relaxed opacity-80">
                    {reason === "revoked" ? t("session_revoked_body") : t("session_expired_body")}
                  </p>
                </div>
              </div>
            )}

            {/* Formulaire */}
            <LoginForm />

            {/* Mot de passe oublié */}
            <div className="mt-5 text-center">
              <button
                type="button"
                className="text-[13px] font-medium transition hover:underline underline-offset-2"
                style={{ color: C.navy }}
              >
                {t("forgot_password")}
              </button>
            </div>

            {/* Note accès */}
            <p className="mt-12 text-center text-[11px] leading-relaxed text-slate-400">
              {t("footerNote")}
            </p>
          </div>
        </div>

        {/* Copyright + lien admin discret */}
        <div className="py-5 text-center text-[11px] text-slate-300 space-y-1.5">
          <div>© {new Date().getFullYear()} ACREMAC — Tous droits réservés</div>
          <div>
            <a
              href="https://gestion.acx-acremac.net"
              className="text-slate-300 hover:text-slate-500 transition underline-offset-2 hover:underline"
            >
              Administration
            </a>
          </div>
        </div>
      </section>
    </main>
  )
}
