'use client';

import { useEffect, useRef, useState, type ReactNode } from 'react';
import { compactNumber, niceScale, type ChartModel } from '../model';
import type { ChartType } from './icons';

/** The report's chart (design `chartSvg` / `pieHtml` / `kpiBigHtml`), with its hover tooltip. */

const col = (i: number) => `var(--sa-s${(i % 8) + 1})`;
const trunc = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);

interface Tip {
  x: number;
  y: number;
  ci: number;
}

export function ReportChart({
  model,
  type,
  measure,
  fmt,
  kpi,
}: {
  model: ChartModel;
  type: ChartType;
  /** The measure's name (axis title, tooltip). */
  measure: string;
  fmt: (v: number) => string;
  /** The KPI view: the big figure and its change. */
  kpi: ReactNode;
}) {
  const boxRef = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(640);
  const [tip, setTip] = useState<Tip | null>(null);
  useEffect(() => {
    const el = boxRef.current;
    if (!el || typeof ResizeObserver === 'undefined') return;
    const ro = new ResizeObserver(() => setWidth(Math.max(320, el.clientWidth || 640)));
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  const { series, cats, stacked } = model;
  const valueOf = (c: ChartModel['cats'][number], id: string) => c.ser[id] ?? 0;
  const hover = (ci: number) => (e: React.MouseEvent) => setTip({ x: e.clientX, y: e.clientY, ci });
  const W = width;
  let body: ReactNode = null;

  if (type === 'kpi') {
    body = kpi;
  } else if (type === 'donut' || type === 'pie') {
    // A split report shares out its series; otherwise the rows share out the value.
    const items = (
      stacked
        ? series.map((s, i) => ({
            l: s.label,
            v: cats.reduce((a, c) => a + valueOf(c, s.id), 0),
            i,
          }))
        : cats.slice(0, 8).map((c, i) => ({ l: c.label, v: c.total, i }))
    ).filter((x) => x.v > 0);
    const sum = items.reduce((a, x) => a + x.v, 0) || 1;
    const cx = 120;
    const cy = 120;
    const ro = 108;
    const ri = type === 'donut' ? 64 : 0;
    const pt = (r: number, a: number) =>
      `${(cx + Math.cos(a) * r).toFixed(2)} ${(cy + Math.sin(a) * r).toFixed(2)}`;
    let a0 = -Math.PI / 2;
    const segs = items.map((x) => {
      const a1 = a0 + (x.v / sum) * Math.PI * 2;
      const big = a1 - a0 > Math.PI ? 1 : 0;
      let d: string;
      if (items.length === 1) {
        d = ri
          ? `M${pt(ro, 0)}A${ro} ${ro} 0 1 1 ${pt(ro, Math.PI)}A${ro} ${ro} 0 1 1 ${pt(ro, 0)}M${pt(ri, 0)}A${ri} ${ri} 0 1 0 ${pt(ri, Math.PI)}A${ri} ${ri} 0 1 0 ${pt(ri, 0)}`
          : `M${cx} ${cy - ro}A${ro} ${ro} 0 1 1 ${cx} ${cy + ro}A${ro} ${ro} 0 1 1 ${cx} ${cy - ro}`;
      } else {
        d = `M${pt(ro, a0)}A${ro} ${ro} 0 ${big} 1 ${pt(ro, a1)}${
          ri ? `L${pt(ri, a1)}A${ri} ${ri} 0 ${big} 0 ${pt(ri, a0)}Z` : `L${cx} ${cy}Z`
        }`;
      }
      a0 = a1;
      return (
        <path
          key={x.l}
          d={d}
          fill={col(x.i)}
          fillRule="evenodd"
          stroke="var(--sa-surface)"
          strokeWidth="2"
          className="sa-slice"
        >
          <title>{`${x.l}: ${fmt(x.v)} (${Math.round((x.v / sum) * 100)}%)`}</title>
        </path>
      );
    });
    body = (
      <div className="sa-pie2">
        <svg
          viewBox="0 0 240 240"
          width="240"
          height="240"
          role="img"
          aria-label={`${measure} share. Values are in the data table.`}
        >
          {segs}
          {ri ? (
            <>
              <text x="120" y="118" textAnchor="middle" className="sa-svg__big">
                {compactNumber(sum)}
              </text>
              <text x="120" y="138" textAnchor="middle" className="sa-svg__sm">
                Total
              </text>
            </>
          ) : null}
        </svg>
        <ul className="sa-leg2 sa-leg2--col">
          {items.map((x) => (
            <li key={x.l}>
              <i className="sa-dot" style={{ background: col(x.i) }} />
              {x.l}
              <strong>
                {fmt(x.v)} ({Math.round((x.v / sum) * 100)}%)
              </strong>
            </li>
          ))}
        </ul>
      </div>
    );
  } else if (type === 'hbar') {
    const shown = cats.slice(0, 60);
    const rowH = 14;
    const gap = 12;
    const L = Math.min(150, Math.max(90, W * 0.22));
    const Rm = 64;
    const T = 6;
    const B = 50;
    const iw = W - L - Rm;
    // Side by side series get a row each inside the category.
    const lanes = stacked ? 1 : series.length;
    const band = rowH * lanes + gap;
    const ih = shown.length * band;
    const mx = Math.max(
      0,
      ...shown.map((c) => (stacked ? c.total : Math.max(...series.map((s) => valueOf(c, s.id))))),
    );
    const sc = niceScale(mx, 6);
    const ticks = Math.round(sc.max / sc.step);
    body = (
      <svg
        className="sa-svg2"
        width={W}
        height={T + ih + B}
        viewBox={`0 0 ${W} ${T + ih + B}`}
        role="img"
        aria-label={`${measure}, horizontal bar chart. Values are in the data table.`}
      >
        {Array.from({ length: ticks + 1 }, (_, i) => {
          const gx = L + (iw * i) / ticks;
          return (
            <g key={i}>
              <line className="sa-svg__grid" x1={gx} x2={gx} y1={T} y2={T + ih} />
              <text className="sa-svg__ax" x={gx} y={T + ih + 18} textAnchor="middle">
                {compactNumber(sc.step * i)}
              </text>
            </g>
          );
        })}
        <line className="sa-svg__base" x1={L} x2={L} y1={T} y2={T + ih} />
        <text className="sa-svg__axt" x={L + iw / 2} y={T + ih + 40} textAnchor="middle">
          {measure}
        </text>
        {shown.map((c, r) => {
          const y0 = T + r * band + gap / 2;
          let x = L;
          return (
            <g
              key={c.key}
              className="sa-hit"
              onMouseMove={hover(r)}
              onMouseLeave={() => setTip(null)}
            >
              <rect x="0" y={y0 - gap / 2} width={W} height={band} fill="transparent" />
              <text
                className="sa-svg__ax sa-svg__cat"
                x={L - 8}
                y={y0 + (rowH * lanes) / 2 + 4}
                textAnchor="end"
              >
                {trunc(c.label, 18)}
              </text>
              {series.map((s, si) => {
                const v = valueOf(c, s.id);
                if (v <= 0) return null;
                const w = (v / sc.max) * iw;
                const rect = (
                  <rect
                    key={s.id}
                    className="sa-seg-r"
                    x={x}
                    y={stacked ? y0 : y0 + si * rowH}
                    width={Math.max(1, w)}
                    height={rowH}
                    fill={col(si)}
                  />
                );
                if (stacked) x += w;
                return rect;
              })}
              <text
                className="sa-svg__val"
                x={(stacked ? x : L + (c.total / sc.max) * iw) + 6}
                y={y0 + rowH - 3}
              >
                {fmt(c.total)}
              </text>
            </g>
          );
        })}
      </svg>
    );
  } else if (type === 'vbar' || type === 'line' || type === 'area') {
    const shown = cats.slice(0, 24);
    const n = shown.length || 1;
    const pl = 52;
    const pr = 16;
    const pt = 22;
    const pb = 54;
    const H = 300;
    const iw = W - pl - pr;
    const ih = H - pt - pb;
    const band = iw / n;
    const maxv = Math.max(
      0,
      ...shown.map((c) =>
        type === 'vbar' && stacked ? c.total : Math.max(...series.map((s) => valueOf(c, s.id))),
      ),
    );
    const sc = niceScale(maxv, 5);
    const tk = Math.round(sc.max / sc.step);
    const per = Math.max(1, Math.ceil(n / Math.max(2, Math.floor(iw / 70))));
    const yOf = (v: number) => pt + ih - (v / sc.max) * ih;
    body = (
      <svg
        className="sa-svg2"
        width={W}
        height={H}
        viewBox={`0 0 ${W} ${H}`}
        role="img"
        aria-label={`${measure} chart. Values are in the data table.`}
      >
        {Array.from({ length: tk + 1 }, (_, i) => {
          const gy = pt + ih - (ih * i) / tk;
          return (
            <g key={i}>
              <line className="sa-svg__grid" x1={pl} x2={W - pr} y1={gy} y2={gy} />
              <text className="sa-svg__ax" x={pl - 8} y={gy + 4} textAnchor="end">
                {compactNumber(sc.step * i)}
              </text>
            </g>
          );
        })}
        {shown.map((c, r) =>
          r % per === 0 ? (
            <text
              key={c.key}
              className="sa-svg__ax"
              x={pl + band * r + band / 2}
              y={pt + ih + 18}
              textAnchor="middle"
            >
              {trunc(c.label, 10)}
            </text>
          ) : null,
        )}
        {type === 'vbar' ? (
          shown.map((c, r) => {
            const lanes = stacked ? 1 : series.length;
            const w = (band * 0.6) / lanes;
            let y = pt + ih;
            return (
              <g
                key={c.key}
                className="sa-hit"
                onMouseMove={hover(r)}
                onMouseLeave={() => setTip(null)}
              >
                <rect x={pl + band * r} y={pt} width={band} height={ih} fill="transparent" />
                {series.map((s, si) => {
                  const v = valueOf(c, s.id);
                  if (v <= 0) return null;
                  const h = (v / sc.max) * ih;
                  const x = pl + band * r + band * 0.2 + (stacked ? 0 : si * w);
                  const top = stacked ? (y -= h) : pt + ih - h;
                  return (
                    <rect
                      key={s.id}
                      className="sa-seg-r"
                      x={x}
                      y={top}
                      width={w}
                      height={Math.max(1, h)}
                      fill={col(si)}
                    />
                  );
                })}
              </g>
            );
          })
        ) : (
          <>
            {series.map((s, si) => {
              const pts = shown.map(
                (c, r) => [pl + band * r + band / 2, yOf(valueOf(c, s.id))] as const,
              );
              const ln = pts
                .map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(1)} ${p[1].toFixed(1)}`)
                .join('');
              return (
                <g key={s.id}>
                  {type === 'area' && pts.length ? (
                    <path
                      d={`${ln}L${pts[pts.length - 1]![0]} ${pt + ih}L${pts[0]![0]} ${pt + ih}Z`}
                      fill={col(si)}
                      opacity={series.length === 1 ? 0.2 : 0.16}
                    />
                  ) : null}
                  <path
                    d={ln}
                    fill="none"
                    stroke={col(si)}
                    strokeWidth="2"
                    strokeLinejoin="round"
                  />
                  {pts.map((p, i) => (
                    <circle
                      key={i}
                      className="sa-pt"
                      cx={p[0]}
                      cy={p[1]}
                      r="3.5"
                      fill="var(--sa-surface)"
                      stroke={col(si)}
                      strokeWidth="2"
                    />
                  ))}
                </g>
              );
            })}
            {shown.map((c, r) => (
              <g
                key={c.key}
                className="sa-hit"
                onMouseMove={hover(r)}
                onMouseLeave={() => setTip(null)}
              >
                <rect x={pl + band * r} y={pt} width={band} height={ih} fill="transparent" />
              </g>
            ))}
          </>
        )}
        <line className="sa-svg__base" x1={pl} x2={W - pr} y1={pt + ih} y2={pt + ih} />
        <text className="sa-svg__axt" x={pl + iw / 2} y={H - 6} textAnchor="middle">
          {measure}
        </text>
      </svg>
    );
  }

  const tc = tip ? cats[tip.ci] : null;
  return (
    <div className="sa-chart2" ref={boxRef}>
      {body}
      {tip && tc ? (
        <div
          className="sa-ctip"
          style={{
            position: 'fixed',
            left: Math.min(
              tip.x + 14,
              (typeof window !== 'undefined' ? window.innerWidth : 1200) - 240,
            ),
            top: tip.y - 20,
          }}
        >
          <div className="sa-ctip__h">{tc.label}</div>
          <div className="sa-ctip__m">{measure}</div>
          {series.length > 1
            ? series.map((s, i) => (
                <div className="sa-ctip__r" key={s.id}>
                  <i className="sa-dot" style={{ background: col(i) }} />
                  <span>{s.label}</span>
                  <b>{fmt(valueOf(tc, s.id))}</b>
                  {stacked ? (
                    <em>({tc.total ? Math.round((valueOf(tc, s.id) / tc.total) * 100) : 0}%)</em>
                  ) : null}
                </div>
              ))
            : null}
          <div className="sa-ctip__t">
            <span>Totals:</span>
            <b>{fmt(tc.total)}</b>
          </div>
        </div>
      ) : null}
    </div>
  );
}
