"use client";

import { useEffect, useState } from "react";
import { useTranslations, useLocale } from "next-intl";
import { ShieldX, LogOut, Phone, RefreshCw } from "lucide-react";
import { logout } from "@/src/lib/api/auth-session";
import { useRouter } from "next/navigation";

type ExpiredPayload = {
  plan?: string
  expires_at?: string | null
  days_remaining?: number
}

const NAVY  = "#1a3578";
const NAVY2 = "#2655b0";
const RED   = "#dc2626";

function fmt(iso: string | null | undefined, locale: string) {
  if (!iso) return "—";
  try {
    return new Date(iso).toLocaleDateString(locale === "fr" ? "fr-FR" : "en-GB", {
      day: "2-digit", month: "long", year: "numeric",
    });
  } catch {
    return iso;
  }
}

export function SubscriptionGate() {
  const t      = useTranslations("subscription_gate");
  const locale = useLocale();
  const router = useRouter();

  const [data, setData] = useState<ExpiredPayload | null>(null);
  const [loggingOut, setLoggingOut] = useState(false);

  useEffect(() => {
    function onExpired(e: Event) {
      const detail = (e as CustomEvent<ExpiredPayload>).detail;
      setData(detail ?? {});
    }
    window.addEventListener("subscription:expired", onExpired);
    return () => window.removeEventListener("subscription:expired", onExpired);
  }, []);

  if (!data) return null;

  async function onLogout() {
    setLoggingOut(true);
    try { await logout(); } finally {
      router.replace(`/${locale}/login`);
    }
  }

  return (
    /* Overlay plein écran, non-dismissible */
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center p-4"
      style={{
        background: "rgba(10,14,40,0.85)",
        backdropFilter: "blur(12px)",
        WebkitBackdropFilter: "blur(12px)",
      }}
    >
      {/* Carte centrale */}
      <div
        className="relative w-full max-w-md rounded-3xl overflow-hidden shadow-2xl"
        style={{ background: "#fff" }}
      >
        {/* Bande supérieure colorée */}
        <div
          className="h-2 w-full"
          style={{ background: `linear-gradient(90deg, ${RED} 0%, #f97316 100%)` }}
        />

        <div className="px-8 py-8 flex flex-col items-center text-center gap-5">

          {/* Icône */}
          <div
            className="flex h-20 w-20 items-center justify-center rounded-2xl shadow-lg"
            style={{
              background: "linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%)",
              border: "1.5px solid #fecaca",
            }}
          >
            <ShieldX className="h-10 w-10" style={{ color: RED }} />
          </div>

          {/* Titre */}
          <div>
            <h1 className="text-2xl font-extrabold text-slate-900 leading-tight">
              {t("title")}
            </h1>
            <p className="mt-1.5 text-sm text-slate-500">{t("subtitle")}</p>
          </div>

          {/* Informations licence */}
          <div
            className="w-full rounded-2xl px-5 py-4 space-y-2 text-left"
            style={{ background: "#f8fafc", border: "1px solid #e2e8f0" }}
          >
            {data.plan && (
              <div className="flex items-center justify-between text-sm">
                <span className="text-slate-500 font-medium">{t("plan")}</span>
                <span
                  className="rounded-full px-3 py-0.5 text-xs font-bold"
                  style={{ background: `${NAVY}12`, color: NAVY }}
                >
                  {data.plan === "annual"   ? t("plan_annual")
                   : data.plan === "lifetime" ? t("plan_lifetime")
                   : data.plan}
                </span>
              </div>
            )}
            {data.expires_at && (
              <div className="flex items-center justify-between text-sm">
                <span className="text-slate-500 font-medium">{t("expired_on")}</span>
                <span className="font-semibold text-red-600">{fmt(data.expires_at, locale)}</span>
              </div>
            )}
          </div>

          {/* Message */}
          <p className="text-sm text-slate-600 leading-relaxed">
            {t("message")}
          </p>

          {/* Contact */}
          <div
            className="w-full flex items-center gap-3 rounded-xl px-4 py-3"
            style={{ background: `${NAVY}08`, border: `1px solid ${NAVY}18` }}
          >
            <Phone className="h-4 w-4 shrink-0" style={{ color: NAVY }} />
            <span className="text-xs text-slate-600">{t("contact_hint")}</span>
          </div>

          {/* Actions */}
          <div className="w-full flex flex-col gap-2.5 pt-1">
            <button
              onClick={() => window.location.reload()}
              className="flex items-center justify-center gap-2 w-full rounded-xl py-2.5 text-sm font-semibold border transition hover:bg-slate-50"
              style={{ borderColor: "#e2e8f0", color: "#475569" }}
            >
              <RefreshCw className="h-4 w-4" />
              {t("retry")}
            </button>

            <button
              onClick={onLogout}
              disabled={loggingOut}
              className="flex items-center justify-center gap-2 w-full rounded-xl py-2.5 text-sm font-semibold text-white transition disabled:opacity-50"
              style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}
            >
              <LogOut className="h-4 w-4" />
              {loggingOut ? t("logging_out") : t("logout")}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
