"use client"

import Image from "next/image"
import { useMemo } from "react"
import { useLocale, useTranslations } from "next-intl"
import { ShieldCheck, FileStack, MessageCircle, LifeBuoy, AlertCircle } from "lucide-react"
import { useSearchParams } from "next/navigation"

import { ClientLoginForm } from "@/src/features/client-portal-auth/login-form"
import { useClientAuthGuard } from "@/src/features/client-portal-auth/use-client-auth-guard"
import { FullPageLoader } from "@/src/components/app/FullPageLoader"
import { LocaleSwitcher } from "@/src/components/LocaleSwitcher"

// ── Palette extraite du logo ACX ──────────────────────────────────────────
// Portail client : teal dominant, marine en accent (inverse du login agent)
const C = {
  teal:      "#3aaa87",   // teal principal (légèrement plus profond)
  tealMid:   "#2d9073",   // teal intermédiaire
  tealDeep:  "#1f7560",   // teal profond
  navy:      "#1a3578",   // marine (accent)
  navyLight: "#2655b0",   // marine clair
  white:     "#ffffff",
}

export default function ClientLoginPage() {
  const t = useTranslations("clientPortalAuth")
  const locale = useLocale()
  const searchParams = useSearchParams()

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

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

  if (checking) return <FullPageLoader />

  const features = [
    { icon: FileStack,     title: t("feature1Title"), body: t("feature1Body") },
    { icon: MessageCircle, title: t("feature2Title"), body: t("feature2Body") },
    { icon: LifeBuoy,      title: t("feature3Title"), body: t("feature3Body") },
  ]

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

      {/* ── PANNEAU GAUCHE — teal dominant ───────────────────────────────── */}
      <section
        className="relative hidden lg:flex flex-col h-full overflow-hidden select-none"
        style={{
          background: `linear-gradient(155deg, ${C.tealDeep} 0%, ${C.tealMid} 45%, ${C.teal} 100%)`,
        }}
      >
        {/* Halos décoratifs */}
        <div className="pointer-events-none absolute inset-0 overflow-hidden">
          {/* Halo marine (contraste) en haut à droite */}
          <div
            className="absolute -top-28 -right-28 h-[500px] w-[500px] rounded-full opacity-[0.18]"
            style={{ background: `radial-gradient(circle, ${C.navy}, transparent 65%)` }}
          />
          {/* Halo blanc doux en bas */}
          <div
            className="absolute -bottom-40 left-0 h-[420px] w-[420px] rounded-full opacity-[0.08]"
            style={{ background: `radial-gradient(circle, #ffffff, transparent 70%)` }}
          />
          {/* Grille de points */}
          <svg className="absolute inset-0 h-full w-full opacity-[0.07]" xmlns="http://www.w3.org/2000/svg">
            <defs>
              <pattern id="cp-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(#cp-dots)" />
          </svg>
        </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(255,255,255,0.18)",
                  borderColor: "rgba(255,255,255,0.25)",
                }}
              >
                <ShieldCheck className="h-4 w-4 text-white" />
              </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(255,255,255,0.12)",
                borderColor: "rgba(255,255,255,0.20)",
              }}
            >
              <span className="relative flex h-2 w-2">
                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-white opacity-60" />
                <span className="relative inline-flex h-2 w-2 rounded-full bg-white" />
              </span>
              <span className="text-xs font-medium text-white/80">ACX · Portail Client</span>
            </div>

            {/* Titre */}
            <h1 className="max-w-xs 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/60">
              {t("heroSubtitle")}
            </p>

            {/* Feature list */}
            <ul className="mt-12 space-y-5">
              {features.map(({ icon: Icon, title, body }) => (
                <li key={title} className="flex items-start gap-4">
                  <div
                    className="flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl ring-1"
                    style={{
                      background: "rgba(255,255,255,0.12)",
                      borderColor: "rgba(255,255,255,0.18)",
                    }}
                  >
                    <Icon className="h-4 w-4 text-white" />
                  </div>
                  <div className="pt-0.5">
                    <p className="text-sm font-semibold text-white">{title}</p>
                    <p className="mt-0.5 text-xs leading-relaxed text-white/50">{body}</p>
                  </div>
                </li>
              ))}
            </ul>
          </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 bg-[#f5fbf8]">
        <div className="flex flex-1 flex-col items-center justify-center px-8 py-16 sm:px-12">
          <div className="w-full max-w-[360px]">

            {/* 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.75rem] font-bold tracking-tight"
                style={{ color: C.tealDeep }}
              >
                {t("title")}
              </h2>
              <p className="mt-2 text-[15px] text-slate-500">{t("subtitle")}</p>
            </div>

            {/* Bannière session expirée / mot de passe changé */}
            {reason && (
              <div
                className="mb-7 flex items-start gap-3 rounded-2xl border px-4 py-3.5 text-sm"
                style={reason === "password_changed" ? {
                  borderColor: "rgba(58,170,135,0.25)",
                  background: "rgba(240,253,250,0.95)",
                  color: "#1f7560",
                } : {
                  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"          ? "Session révoquée"
                     : reason === "password_changed" ? "Mot de passe mis à jour"
                     : "Session expirée"}
                  </p>
                  <p className="mt-0.5 text-xs leading-relaxed opacity-80">
                    {reason === "revoked"
                      ? "Votre session a été révoquée par un administrateur."
                      : reason === "password_changed"
                      ? "Votre mot de passe a été défini avec succès. Connectez-vous avec vos nouveaux identifiants."
                      : "Votre session a expiré. Veuillez vous reconnecter."}
                  </p>
                </div>
              </div>
            )}

            {/* Formulaire */}
            <ClientLoginForm />

            {/* 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.tealMid }}
              >
                {t("forgot_password")}
              </button>
            </div>

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

        {/* Copyright */}
        <div className="py-5 text-center text-[11px] text-slate-300">
          © {new Date().getFullYear()} ACREMAC — Tous droits réservés
        </div>
      </section>
    </main>
  )
}
