import { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { useData, useRepos } from "../../data/DataContext";
import { useI18n } from "../../i18n/I18nContext";
import { getPlanRights } from "../../lib/planRights";
import type { PlanId, UsageMonthSummary } from "../../lib/usageMeter";

/**
 * 頂欄：方案名 + 剩餘點數（可讀文字，不塞細進度條）。
 * 點開再看完整進度、權益與變更方案。
 */
export function UsagePlanWidget() {
  const repos = useRepos();
  const { tick } = useData();
  const { t, formatPlanPrice } = useI18n();
  const [summary, setSummary] = useState<UsageMonthSummary | null>(null);
  const [open, setOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    let alive = true;
    void repos.usage.getSummary().then((s) => {
      if (alive) setSummary(s);
    });
    return () => {
      alive = false;
    };
  }, [repos.usage, tick]);

  useEffect(() => {
    function onDoc(e: MouseEvent) {
      if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);

  if (!summary) {
    return (
      <span className="hb-usage-widget hb-usage-widget--ghost" aria-hidden>
        …
      </span>
    );
  }

  const planId = summary.plan.id as PlanId;
  const rights = getPlanRights(planId, t, formatPlanPrice);
  // 上限一律用目前方案 PLANS 配給（summary.plan 已由 live repo 綁定 PLANS）
  const cap = summary.plan.monthly_credits;
  const used = summary.platform?.credits_used ?? summary.total_credits;
  const left = summary.unlimited
    ? Math.max(0, summary.remaining_credits)
    : Math.max(0, cap - used);
  const pct =
    summary.pct > 0
      ? Math.min(100, summary.pct)
      : cap > 0
        ? Math.min(100, Math.round((used / cap) * 100))
        : 0;
  const tight = !summary.unlimited && (pct >= 70 || used >= cap);
  const over = !summary.unlimited && used > cap;
  const isFree = planId === "free";
  const price = formatPlanPrice(summary.plan.price_twd);

  const triggerHint = summary.unlimited
    ? t("usage.widget.titleUnlimited", { name: summary.plan.name })
    : t("usage.widget.titleUsed", { name: summary.plan.name, used, cap });

  return (
    <div
      className={["hb-usage-widget", `is-plan-${planId}`].join(" ")}
      ref={rootRef}
      data-plan={planId}
    >
      <button
        type="button"
        className={[
          "hb-usage-widget__trigger",
          `is-plan-${planId}`,
          open ? "is-open" : "",
          tight ? "is-tight" : "",
          isFree ? "is-free" : "",
        ]
          .filter(Boolean)
          .join(" ")}
        onClick={() => setOpen((v) => !v)}
        aria-expanded={open}
        aria-haspopup="dialog"
        title={triggerHint}
      >
        <span className="hb-usage-widget__badge">{summary.plan.name}</span>
        <span className="hb-usage-widget__sep" aria-hidden>
          ·
        </span>
        {summary.unlimited ? (
          <span className="hb-usage-widget__stat" title={t("usage.widget.unlimited")}>
            ∞
          </span>
        ) : over ? (
          <span className="hb-usage-widget__stat hb-usage-widget__stat--warn">
            {t("usage.widget.overShort")}
          </span>
        ) : (
          // 一律顯示 已用/上限，避免「還剩 80」被看成「上限 80」（Free 是 120）
          <span
            className={[
              "hb-usage-widget__stat",
              isFree && pct < 70 ? "hb-usage-widget__stat--cta" : "",
              tight ? "hb-usage-widget__stat--warn" : "",
            ]
              .filter(Boolean)
              .join(" ")}
            title={t("usage.widget.titleUsed", { name: summary.plan.name, used, cap })}
          >
            {t("usage.widget.usedOfCap", { used, cap })}
          </span>
        )}
      </button>

      {open ? (
        <div
          className="hb-usage-widget__panel"
          role="dialog"
          aria-label={t("usage.widget.dialog")}
        >
          <div className="hb-usage-widget__head">
            <div className="hb-usage-widget__head-main">
              <span className="hb-usage-widget__eyebrow">{t("usage.widget.currentPlan")}</span>
              <strong className="hb-usage-widget__head-plan">
                {summary.plan.name}
                {summary.unlimited ? (
                  <span className="hb-usage-widget__inf" title={t("usage.widget.unlimited")}>
                    {" "}
                    ∞
                  </span>
                ) : null}
              </strong>
              <span className="hb-usage-widget__price">
                {price}
                <span className="hb-usage-widget__period">{t("usage.widget.perMonth")}</span>
              </span>
            </div>
            <div className="hb-usage-widget__head-use">
              <span className="hb-usage-widget__eyebrow">{t("usage.widget.monthUsage")}</span>
              <strong className="hb-usage-widget__head-num">
                {used}
                <span className="hb-usage-widget__cap">/{cap}</span>
              </strong>
              <span className="hb-usage-widget__left">
                {summary.unlimited
                  ? t("usage.widget.unlimited")
                  : t("usage.widget.remaining", { n: left })}
              </span>
            </div>
          </div>

          {!summary.unlimited ? (
            <div
              className="hb-usage-widget__track"
              role="meter"
              aria-valuenow={used}
              aria-valuemin={0}
              aria-valuemax={cap}
              aria-label={t("usage.widget.ariaUsed", { used, cap })}
            >
              <div
                className={`hb-usage-widget__track-fill${over ? " is-over" : tight ? " is-warn" : ""}`}
                style={{ width: `${Math.min(100, pct)}%` }}
              />
            </div>
          ) : null}

          <ul className="hb-usage-widget__bullets">
            {rights.bullets.map((b) => (
              <li key={b}>{b}</li>
            ))}
          </ul>
          <p className="hb-usage-widget__caps">{rights.approxCallsLine}</p>
          <p className="hb-usage-widget__caps hb-usage-widget__caps--pts">{rights.softCapsLine}</p>

          {tight ? <p className="hb-usage-widget__nudge">{t("usage.widget.nudge")}</p> : null}

          <div className="hb-usage-widget__actions">
            <Link
              to="/app/usage/plans"
              className="hb-btn hb-btn--primary hb-usage-widget__btn"
              onClick={() => setOpen(false)}
            >
              {isFree || tight ? t("usage.widget.upgrade") : t("usage.widget.changePlan")}
            </Link>
            <Link
              to="/app/usage"
              className="hb-btn hb-btn--ghost hb-usage-widget__btn"
              onClick={() => setOpen(false)}
            >
              {t("usage.widget.usageDetail")}
            </Link>
          </div>
        </div>
      ) : null}
    </div>
  );
}
