import * as React from "react";

interface Series {
  label: string;
  color: string;
  values: number[];
}

interface LineChartProps {
  labels: string[];
  series: Series[];
  height?: number;
}

/**
 * Minimal dependency-free SVG line chart for the dashboard's daily metrics.
 * Renders one polyline per series against a shared 0..max y-scale.
 */
export function LineChart({ labels, series, height = 240 }: LineChartProps) {
  const width = 720;
  const padding = 32;
  const max = Math.max(1, ...series.flatMap((s) => s.values));
  const stepX = labels.length > 1 ? (width - padding * 2) / (labels.length - 1) : 0;
  const [hoverIndex, setHoverIndex] = React.useState<number | null>(null);

  // Tooltip geometry (SVG units)
  const tipWidth = 150;
  const tipHeight = 20 + series.length * 16;
  const tipGap = 8;
  const hoverX = hoverIndex !== null ? padding + hoverIndex * stepX : 0;
  // Prefer the right of the hover line; flip to the left if it would overflow
  const flipped = hoverX + tipGap + tipWidth > width - 4;
  const tipX = Math.max(4, flipped ? hoverX - tipGap - tipWidth : hoverX + tipGap);

  function point(i: number, value: number) {
    const x = padding + i * stepX;
    const y = height - padding - (value / max) * (height - padding * 2);
    return `${x},${y}`;
  }

  // Convert a screen-pixel clientX into the nearest data index.
  // The SVG is scaled by its viewBox, so screen px must be mapped to viewBox units.
  function updateHover(clientX: number, target: SVGRectElement) {
    if (stepX <= 0) {
      setHoverIndex(labels.length > 0 ? 0 : null);
      return;
    }
    const rect = target.getBoundingClientRect();
    if (rect.width === 0) return;
    const x = ((clientX - rect.left) / rect.width) * (width - padding * 2);
    const index = Math.round(x / stepX);
    if (index >= 0 && index < labels.length) {
      setHoverIndex(index);
    }
  }

  return (
    <div className="w-full overflow-x-auto">
      <svg viewBox={`0 0 ${width} ${height}`} className="min-w-[560px]" role="img" aria-label="Daily metrics chart">
        {[0, 0.25, 0.5, 0.75, 1].map((t) => (
          <g key={t}>
            <line
              x1={padding}
              x2={width - padding}
              y1={height - padding - t * (height - padding * 2)}
              y2={height - padding - t * (height - padding * 2)}
              stroke="var(--color-border)"
              strokeWidth={1}
            />
            <text
              x={padding - 8}
              y={height - padding - t * (height - padding * 2) + 3}
              fontSize={10}
              fill="var(--color-ink-faint)"
              textAnchor="end"
            >
              {Math.round(max * t)}
            </text>
          </g>
        ))}
        {series.map((s) => (
          <polyline
            key={s.label}
            fill="none"
            stroke={s.color}
            strokeWidth={2}
            points={s.values.map((v, i) => point(i, v)).join(" ")}
          />
        ))}
        {labels.map((label, i) =>
          i % Math.ceil(labels.length / 8 || 1) === 0 ? (
            <text key={label} x={padding + i * stepX} y={height - 8} fontSize={10} fill="var(--color-ink-faint)" textAnchor="middle">
              {label.slice(5)}
            </text>
          ) : null
        )}
        {hoverIndex !== null && (
          <g pointerEvents="none">
            <line
              x1={hoverX}
              x2={hoverX}
              y1={padding}
              y2={height - padding}
              stroke="var(--color-border)"
              strokeWidth={1}
              strokeDasharray="4 4"
            />
            <rect
              x={tipX}
              y={padding}
              width={tipWidth}
              height={tipHeight}
              fill="var(--color-surface)"
              stroke="var(--color-border)"
              rx={4}
            />
            <text x={tipX + 8} y={padding + 14} fontSize={11} fill="var(--color-ink)" fontWeight="600">
              {labels[hoverIndex]}
            </text>
            {series.map((s, idx) => (
              <text
                key={s.label}
                x={tipX + 8}
                y={padding + 30 + idx * 16}
                fontSize={10}
                fill={s.color}
              >
                {s.label}: {s.values[hoverIndex]}
              </text>
            ))}
          </g>
        )}
        <rect
          x={padding}
          y={padding}
          width={width - padding * 2}
          height={height - padding * 2}
          fill="transparent"
          style={{ touchAction: "pan-y" }}
          onMouseMove={(e) => updateHover(e.clientX, e.currentTarget)}
          onMouseLeave={() => setHoverIndex(null)}
          onTouchStart={(e) => updateHover(e.touches[0].clientX, e.currentTarget)}
          onTouchMove={(e) => updateHover(e.touches[0].clientX, e.currentTarget)}
          onTouchEnd={() => setHoverIndex(null)}
        />
      </svg>
      <div className="mt-3 flex flex-wrap gap-4">
        {series.map((s) => (
          <span key={s.label} className="flex items-center gap-1.5 text-xs text-(--color-ink-muted)">
            <span className="h-2 w-2 rounded-full" style={{ background: s.color }} />
            {s.label}
          </span>
        ))}
      </div>
    </div>
  );
}