'use client';

import { useEffect, useRef, useState } from 'react';
import { fmtDay, type Metric, nice, niceStep } from './analyticsModel';

/**
 * PB5: "Playbook Usage Over Time" (playbooks.js:673-739): an SVG line per series, six gridlines,
 * left axis Total Views (Total Logs when alone), right axis Total Logs with both, M/D/YYYY dates
 * about every 84 px, and a hover cursor with the bucket's counts.
 */
export function UsageChart({
  starts,
  vals,
  metric,
}: {
  starts: string[];
  vals: Array<[number, number]>;
  metric: Metric;
}) {
  const box = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(720);
  const [hot, setHot] = useState<number | null>(null);

  useEffect(() => {
    const el = box.current;
    if (!el) return;
    const measure = () => setWidth(Math.max(el.clientWidth, 320));
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  const showV = metric !== 'logs';
  const showL = metric !== 'views';
  const stepV = niceStep(Math.max(0, ...vals.map((v) => v[0])));
  const stepL = niceStep(Math.max(0, ...vals.map((v) => v[1])));
  const W = width;
  const H = W < 560 ? 300 : 380;
  const pad = { l: 64, r: showV && showL ? 64 : 24, t: 16, b: 58 };
  const iw = W - pad.l - pad.r;
  const ih = H - pad.t - pad.b;
  const n = starts.length;
  const x = (i: number) => pad.l + (n === 1 ? iw / 2 : (iw * i) / (n - 1));
  const y = (v: number, step: number) => pad.t + ih - (v / (step * 5)) * ih;
  const per = Math.max(1, Math.ceil(n / Math.max(2, Math.floor(iw / 84))));
  const leftStep = showV ? stepV : stepL;

  const onMove = (clientX: number) => {
    const r = box.current?.getBoundingClientRect();
    if (!r || !n) return;
    const px = clientX - r.left;
    let best = 0;
    let bd = Infinity;
    for (let i = 0; i < n; i++) {
      const d = Math.abs(x(i) - px);
      if (d < bd) {
        bd = d;
        best = i;
      }
    }
    setHot(best);
  };

  const series = (idx: 0 | 1, cls: 'views' | 'logs', step: number) => (
    <>
      <polyline
        className={`pbl-line pbl-line--${cls}`}
        fill="none"
        points={vals.map((v, i) => `${x(i)},${y(v[idx], step)}`).join(' ')}
      />
      {vals.map((v, i) => (
        <circle
          key={i}
          className={`pbl-pt pbl-pt--${cls}${hot === i ? 'is-hot' : ''}`}
          cx={x(i)}
          cy={y(v[idx], step)}
          r={n > 60 ? 0 : 4}
        />
      ))}
    </>
  );

  const tipLeft = hot === null ? 0 : x(hot) + 14;
  return (
    <div
      className="pbl-chart"
      ref={box}
      onMouseMove={(e) => onMove(e.clientX)}
      onTouchStart={(e) => {
        const t = e.touches[0];
        if (t) onMove(t.clientX);
      }}
      onMouseLeave={() => setHot(null)}
    >
      <svg
        width={W}
        height={H}
        viewBox={`0 0 ${W} ${H}`}
        role="img"
        aria-label="Playbook usage over time"
      >
        {[0, 1, 2, 3, 4, 5].map((g) => {
          const gy = pad.t + ih - (ih * g) / 5;
          return (
            <g key={g}>
              <line
                className={`pbl-grid${g === 0 ? 'pbl-grid--base' : ''}`}
                x1={pad.l}
                x2={W - pad.r}
                y1={gy}
                y2={gy}
              />
              <text className="pbl-axis" x={pad.l - 10} y={gy + 4} textAnchor="end">
                {nice(leftStep * g)}
              </text>
              {showV && showL ? (
                <text className="pbl-axis" x={W - pad.r + 10} y={gy + 4} textAnchor="start">
                  {nice(stepL * g)}
                </text>
              ) : null}
            </g>
          );
        })}
        {starts.map((d, i) =>
          i % per === 0 || (i === n - 1 && per === 1) ? (
            <text key={d} className="pbl-axis" x={x(i)} y={H - pad.b + 20} textAnchor="middle">
              {fmtDay(d)}
            </text>
          ) : null,
        )}
        <text className="pbl-axis-title" x={pad.l + iw / 2} y={H - 10} textAnchor="middle">
          Date
        </text>
        <text
          className={`pbl-axis-title pbl-axis-title--${showV ? 'views' : 'logs'}`}
          transform={`translate(16 ${pad.t + ih / 2}) rotate(-90)`}
          textAnchor="middle"
        >
          {showV ? 'Total Views' : 'Total Logs'}
        </text>
        {showV && showL ? (
          <text
            className="pbl-axis-title pbl-axis-title--logs"
            transform={`translate(${W - 14} ${pad.t + ih / 2}) rotate(90)`}
            textAnchor="middle"
          >
            Total Logs
          </text>
        ) : null}
        {showV ? series(0, 'views', stepV) : null}
        {showL ? series(1, 'logs', stepL) : null}
        {hot !== null ? (
          <line className="pbl-cursor" x1={x(hot)} x2={x(hot)} y1={pad.t} y2={pad.t + ih} />
        ) : null}
      </svg>
      {hot !== null && starts[hot] ? (
        <div
          className="pbl-tooltip"
          style={{ left: Math.max(4, tipLeft + 180 > W - 4 ? x(hot) - 194 : tipLeft), top: 40 }}
        >
          <div className="pbl-tooltip__head">{fmtDay(starts[hot])}</div>
          {showV ? (
            <div className="pbl-tooltip__row">
              <i className="pbl-dot pbl-dot--views" />
              <span>Total Views</span>
              <b>{vals[hot]![0]}</b>
            </div>
          ) : null}
          {showL ? (
            <div className="pbl-tooltip__row">
              <i className="pbl-dot pbl-dot--logs" />
              <span>Total Logs</span>
              <b>{vals[hot]![1]}</b>
            </div>
          ) : null}
        </div>
      ) : null}
    </div>
  );
}
