"use client";

import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { SidebarMenuItem } from "@/components/ui/sidebar";
import { getKeywordQuotaAction } from "@/lib/billing/quota-actions";
import { useActiveSite } from "@/lib/keywords/site-context";

type Quota = { used: number; limit: number };

/** Couleur de la jauge selon le volume restant : vert (large), ambre (se
 *  remplit), rouge (proche/au-delà de la limite). */
function barColor(ratio: number): string {
  if (ratio >= 0.9) return "bg-red-500";
  if (ratio >= 0.7) return "bg-amber-500";
  return "bg-emerald-500";
}

/** Jauge de quota mots-clés sous le sélecteur de site (par org). Masquée quand
 *  le plan est illimité (-1) ou sans donnée. */
export function KeywordQuotaBar() {
  const { activeSiteId } = useActiveSite();
  const pathname = usePathname();
  const [quota, setQuota] = useState<Quota | null>(null);

  useEffect(() => {
    let cancelled = false;
    const load = () => {
      // Re-run triggers: a plan change (Stripe) doesn't remount this persistent
      // sidebar widget, so the limit (e.g. « / 1 500 ») would stay stale. The
      // server read is fresh — only the client needs re-asking on site change
      // (`activeSiteId`, may belong to another org) and on navigation
      // (`pathname`, e.g. coming back from /billing after an upgrade).
      void activeSiteId;
      void pathname;
      getKeywordQuotaAction()
        .then((q) => {
          if (!cancelled) setQuota(q);
        })
        .catch(() => {});
    };
    load();
    // Returning from the Stripe checkout/portal tab → refetch so the new plan's
    // limit shows without a full reload.
    window.addEventListener("focus", load);
    return () => {
      cancelled = true;
      window.removeEventListener("focus", load);
    };
  }, [activeSiteId, pathname]);

  if (!quota || quota.limit <= 0) return null;
  const ratio = Math.min(1, quota.used / quota.limit);
  const pct = Math.round(ratio * 100);

  return (
    <SidebarMenuItem className="px-2 pt-1.5 pb-1 group-data-[collapsible=icon]:hidden">
      <div className="flex items-center justify-between text-[11px] text-sidebar-foreground/70">
        <span>Mots-clés</span>
        <span className="tabular-nums">
          {quota.used.toLocaleString("fr-FR")} /{" "}
          {quota.limit.toLocaleString("fr-FR")}
        </span>
      </div>
      <div className="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-sidebar-accent">
        <div
          className={`h-full rounded-full ${barColor(ratio)} transition-all`}
          style={{ width: `${pct}%` }}
        />
      </div>
    </SidebarMenuItem>
  );
}
