import {
  Line,
  LineChart,
  ReferenceLine,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
  CartesianGrid,
} from "recharts";
import { useMemo } from "react";
import type { AnalysisResult } from "@/lib/electrical";

type Metric = "current" | "voltage";

// Downsample so thousands of points stay smooth on mobile.
function downsample<T>(arr: T[], max = 400): T[] {
  if (arr.length <= max) return arr;
  const step = arr.length / max;
  const out: T[] = [];
  for (let i = 0; i < max; i++) out.push(arr[Math.floor(i * step)]);
  return out;
}

export function PhaseChart({
  result,
  metric,
}: {
  result: AnalysisResult;
  metric: Metric;
}) {
  const data = useMemo(() => {
    const rows = downsample(result.rows);
    return rows.map((r) => ({
      idx: r.rowNumber,
      R: metric === "current" ? r.currents.R : r.voltages.R,
      S: metric === "current" ? r.currents.S : r.voltages.S,
      T: metric === "current" ? r.currents.T : r.voltages.T,
    }));
  }, [result, metric]);

  const warnV = result.referenceVoltage * (1 - result.thresholds.underVoltageWarnPct / 100);

  return (
    <div className="h-64 w-full sm:h-80">
      <ResponsiveContainer width="100%" height="100%">
        <LineChart data={data} margin={{ top: 8, right: 8, bottom: 4, left: -12 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" vertical={false} />
          <XAxis
            dataKey="idx"
            tick={{ fontSize: 11, fill: "var(--color-muted-foreground)" }}
            tickLine={false}
            axisLine={{ stroke: "var(--color-border)" }}
            minTickGap={40}
          />
          <YAxis
            tick={{ fontSize: 11, fill: "var(--color-muted-foreground)" }}
            tickLine={false}
            axisLine={false}
            width={44}
            domain={["auto", "auto"]}
          />
          <Tooltip
            contentStyle={{
              background: "var(--color-popover)",
              border: "1px solid var(--color-border)",
              borderRadius: 12,
              fontSize: 12,
              color: "var(--color-popover-foreground)",
            }}
            labelFormatter={(v) => `Row ${v}`}
          />
          {metric === "voltage" && result.referenceVoltage > 0 && (
            <ReferenceLine
              y={warnV}
              stroke="var(--color-warning)"
              strokeDasharray="6 4"
              label={{
                value: "Under-voltage",
                fontSize: 10,
                fill: "var(--color-warning-foreground)",
                position: "insideBottomRight",
              }}
            />
          )}
          <Line type="monotone" dataKey="R" stroke="var(--color-phase-r)" dot={false} strokeWidth={2} name="Phase R" />
          <Line type="monotone" dataKey="S" stroke="var(--color-phase-s)" dot={false} strokeWidth={2} name="Phase S" />
          <Line type="monotone" dataKey="T" stroke="var(--color-phase-t)" dot={false} strokeWidth={2} name="Phase T" />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}

export function PhaseLegend() {
  const items = [
    { label: "Phase R", color: "var(--color-phase-r)" },
    { label: "Phase S", color: "var(--color-phase-s)" },
    { label: "Phase T", color: "var(--color-phase-t)" },
  ];
  return (
    <div className="flex flex-wrap items-center gap-4">
      {items.map((it) => (
        <span key={it.label} className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
          <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: it.color }} />
          {it.label}
        </span>
      ))}
    </div>
  );
}
