import { useMemo, useState } from "react";
import { useI18n } from "../../i18n/I18nContext";
import type { UsageTimeBucket } from "../../lib/usageMeter";

type Props = {
  series: UsageTimeBucket[];
  /** 未 hover 時顯示的區間總計 */
  totals?: { purchased: number; consumed: number };
  maxLabels?: number;
};

/**
 * 雙長條時間序列：hover／focus 才露出該桶數字，不靠長說明。
 */
export function UsageSeriesChart({ series, totals, maxLabels = 12 }: Props) {
  const { t } = useI18n();
  const [active, setActive] = useState<number | null>(null);

  const maxVal = useMemo(
    () =>
      Math.max(
        1,
        ...series.map((b) => Math.max(b.purchased_credits, b.consumed_credits)),
        totals?.purchased ?? 0,
        totals?.consumed ?? 0,
      ),
    [series, totals],
  );

  if (!series.length) {
    return <div className="hb-usage-chart hb-usage-chart--empty" aria-hidden />;
  }

  const W = 640;
  const H = 200;
  const padL = 8;
  const padR = 8;
  const padT = 8;
  const padB = 28;
  const plotW = W - padL - padR;
  const plotH = H - padT - padB;
  const n = series.length;
  const slot = plotW / n;
  const barW = Math.max(2, Math.min(16, slot * 0.34));
  const gap = Math.max(1, barW * 0.12);
  const showEvery = Math.max(1, Math.ceil(n / maxLabels));

  const focus = active != null ? series[active] : null;
  const readPurchased = focus ? focus.purchased_credits : (totals?.purchased ?? 0);
  const readConsumed = focus ? focus.consumed_credits : (totals?.consumed ?? 0);
  const readLabel = focus?.label ?? "";

  return (
    <div
      className="hb-usage-chart"
      onMouseLeave={() => setActive(null)}
    >
      <div className="hb-usage-chart__readout" aria-live="polite">
        <span className={`hb-usage-chart__period${focus ? " is-focus" : ""}`}>
          {readLabel || t("usage.chart.period")}
        </span>
        <span className="hb-usage-chart__metric hb-usage-chart__metric--buy">
          <i className="hb-usage-chart__dot" aria-hidden />
          <span className="hb-usage-chart__name">{t("usage.chart.allocated")}</span>
          <strong>{readPurchased}</strong>
        </span>
        <span className="hb-usage-chart__metric hb-usage-chart__metric--use">
          <i className="hb-usage-chart__dot" aria-hidden />
          <span className="hb-usage-chart__name">{t("usage.chart.consumed")}</span>
          <strong>{readConsumed}</strong>
        </span>
        {readPurchased > 0 ? (
          <span className="hb-usage-chart__pct" title={t("usage.chart.pctTitle")}>
            {Math.min(999, Math.round((readConsumed / readPurchased) * 100))}%
          </span>
        ) : null}
      </div>

      <svg
        className="hb-usage-chart__svg"
        viewBox={`0 0 ${W} ${H}`}
        role="img"
        aria-label={t("usage.chart.aria")}
      >
        {[0.25, 0.5, 0.75].map((tGrid) => {
          const y = padT + plotH * (1 - tGrid);
          return (
            <line
              key={tGrid}
              x1={padL}
              x2={W - padR}
              y1={y}
              y2={y}
              className="hb-usage-chart__grid"
            />
          );
        })}

        {series.map((b, i) => {
          const cx = padL + slot * i + slot / 2;
          const buyH = (b.purchased_credits / maxVal) * plotH;
          const useH = (b.consumed_credits / maxVal) * plotH;
          const buyX = cx - barW - gap / 2;
          const useX = cx + gap / 2;
          const buyY = padT + plotH - buyH;
          const useY = padT + plotH - useH;
          const showLabel = i % showEvery === 0 || i === n - 1;
          const isOn = active === i;
          return (
            <g
              key={b.key}
              className={`hb-usage-chart__col${isOn ? " is-on" : ""}`}
              onMouseEnter={() => setActive(i)}
              onFocus={() => setActive(i)}
              tabIndex={0}
              role="listitem"
              aria-label={t("usage.chart.colAria", {
                label: b.label,
                purchased: b.purchased_credits,
                consumed: b.consumed_credits,
              })}
            >
              {/* 寬熱區 */}
              <rect
                x={padL + slot * i}
                y={padT}
                width={slot}
                height={plotH}
                className="hb-usage-chart__hit"
              />
              <rect
                x={buyX}
                y={buyY}
                width={barW}
                height={Math.max(0, buyH)}
                rx={2}
                className="hb-usage-chart__bar hb-usage-chart__bar--buy"
              />
              <rect
                x={useX}
                y={useY}
                width={barW}
                height={Math.max(0, useH)}
                rx={2}
                className="hb-usage-chart__bar hb-usage-chart__bar--use"
              />
              {showLabel ? (
                <text x={cx} y={H - 8} textAnchor="middle" className="hb-usage-chart__axis">
                  {b.label}
                </text>
              ) : null}
            </g>
          );
        })}
      </svg>
    </div>
  );
}
