import React, { useId, useMemo } from "react";

const SIZE = 320;
const CENTER = SIZE / 2;
const MAX_RADIUS = 118;
const GRID_LEVELS = 4;

function polarPoint(angleIndex, total, radius) {
  const angle = (Math.PI * 2 * angleIndex) / total - Math.PI / 2;
  return {
    x: CENTER + radius * Math.cos(angle),
    y: CENTER + radius * Math.sin(angle),
  };
}

function polygonPoints(total, radius) {
  return Array.from({ length: total }, (_, index) => {
    const { x, y } = polarPoint(index, total, radius);
    return `${x},${y}`;
  }).join(" ");
}

/**
 * @param {{
 *   series: Array<{ label: string, value: number, tone?: string }>,
 *   loading?: boolean,
 * }} props
 */
export default function DocumentStatusRadarChart({ series = [], loading = false }) {
  const gradientId = useId();
  const total = series.length || 1;

  const maxValue = useMemo(() => {
    const peak = Math.max(0, ...series.map((item) => item.value));
    return Math.max(peak, 1);
  }, [series]);

  const dataPoints = useMemo(
    () =>
      series.map((item, index) => {
        const ratio = item.value / maxValue;
        return polarPoint(index, total, ratio * MAX_RADIUS);
      }),
    [series, maxValue, total]
  );

  const dataPolygon = dataPoints.map((p) => `${p.x},${p.y}`).join(" ");

  if (loading) {
    return (
      <div className="swi-admin-radar swi-panel">
        <p className="swi-muted">Loading document status chart…</p>
      </div>
    );
  }

  return (
    <div className="swi-admin-radar swi-panel">
      <header className="swi-admin-radar__head">
        <div>
          <h2 className="swi-admin-radar__title">Document status overview</h2>
          <p className="swi-admin-radar__desc">
            Spider chart of SWI documents by workflow status.
          </p>
        </div>
      </header>

      <div className="swi-admin-radar__body">
        <div className="swi-admin-radar__chart-wrap">
          <svg
            className="swi-admin-radar__chart"
            viewBox={`0 0 ${SIZE} ${SIZE}`}
            role="img"
            aria-label="Radar chart of SWI document counts by status"
          >
            <defs>
              <linearGradient id={gradientId} x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" stopColor="var(--swi-accent)" stopOpacity="0.45" />
                <stop offset="100%" stopColor="var(--swi-accent)" stopOpacity="0.12" />
              </linearGradient>
            </defs>

            {Array.from({ length: GRID_LEVELS }, (_, level) => {
              const radius = ((level + 1) / GRID_LEVELS) * MAX_RADIUS;
              return (
                <polygon
                  key={radius}
                  points={polygonPoints(total, radius)}
                  className="swi-admin-radar__grid-ring"
                />
              );
            })}

            {series.map((item, index) => {
              const outer = polarPoint(index, total, MAX_RADIUS);
              return (
                <line
                  key={item.label}
                  x1={CENTER}
                  y1={CENTER}
                  x2={outer.x}
                  y2={outer.y}
                  className="swi-admin-radar__axis"
                />
              );
            })}

            <polygon
              points={dataPolygon}
              className="swi-admin-radar__data"
              fill={`url(#${gradientId})`}
            />
            <polygon points={dataPolygon} className="swi-admin-radar__data-outline" />

            {dataPoints.map((point, index) => (
              <g key={series[index]?.label ?? index}>
                <circle
                  cx={point.x}
                  cy={point.y}
                  r={5}
                  className="swi-admin-radar__dot"
                />
                <text
                  x={polarPoint(index, total, MAX_RADIUS + 22).x}
                  y={polarPoint(index, total, MAX_RADIUS + 22).y}
                  className="swi-admin-radar__axis-label"
                  textAnchor="middle"
                  dominantBaseline="middle"
                >
                  {series[index]?.label}
                </text>
              </g>
            ))}
          </svg>
        </div>

        <ul className="swi-admin-radar__legend" aria-label="Status counts">
          {series.map((item) => (
            <li key={item.label} className="swi-admin-radar__legend-item">
              <span
                className={`swi-admin-radar__legend-swatch swi-admin-radar__legend-swatch--${item.tone || "opened"}`}
                aria-hidden
              />
              <span className="swi-admin-radar__legend-label">{item.label}</span>
              <strong className="swi-admin-radar__legend-value">{item.value}</strong>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}
