import { useEffect, useMemo, useRef } from "react";
import { ColorType, LineSeries, createChart, type IChartApi, type ISeriesApi } from "lightweight-charts";

export interface EquityPoint {
  date: string;
  val: number;
}

export interface EquitySeries {
  name: string;
  color: string;
  points: EquityPoint[];
}

function toTime(date: string) {
  return (Date.parse(date + "T00:00:00Z") / 1000) as import("lightweight-charts").UTCTimestamp;
}

export default function EquityChart({ series, heightClass = "equity-chart" }: { series: EquitySeries[]; heightClass?: string }) {
  const ref = useRef<HTMLDivElement>(null);
  const chartRef = useRef<IChartApi | null>(null);
  const lineRefs = useRef<ISeriesApi<"Line">[]>([]);

  const clean = useMemo(
    () =>
      series
        .map((s) => ({
          ...s,
          points: (s.points || []).filter((p) => p.date && p.val != null && !Number.isNaN(p.val)),
        }))
        .filter((s) => s.points.length > 1),
    [series],
  );

  useEffect(() => {
    if (!ref.current) return;
    const chart = createChart(ref.current, {
      layout: { background: { type: ColorType.Solid, color: "transparent" }, textColor: "#e8ecf4", fontSize: 11 },
      grid: { vertLines: { color: "rgba(255,255,255,.06)" }, horzLines: { color: "rgba(255,255,255,.06)" } },
      rightPriceScale: { borderColor: "rgba(231,198,107,.25)" },
      timeScale: { borderColor: "rgba(231,198,107,.25)", timeVisible: true },
      autoSize: true,
    });
    chartRef.current = chart;
    lineRefs.current = clean.map((s) =>
      chart.addSeries(LineSeries, {
        color: s.color,
        lineWidth: 2,
        priceLineVisible: false,
        lastValueVisible: true,
        title: s.name,
      }),
    );
    return () => {
      chart.remove();
      chartRef.current = null;
      lineRefs.current = [];
    };
  }, [clean.length]);

  useEffect(() => {
    clean.forEach((s, i) => {
      const line = lineRefs.current[i];
      if (!line) return;
      line.setData(s.points.map((p) => ({ time: toTime(p.date), value: p.val })));
    });
    chartRef.current?.timeScale().fitContent();
  }, [clean]);

  if (!clean.length) return <p className="muted">無權益曲線資料</p>;

  return (
    <div className="equity-wrap">
      <div className="candle-legend">
        {clean.map((s) => (
          <span key={s.name} className="candle-legend-item">
            <i style={{ background: s.color }} />
            {s.name}
          </span>
        ))}
      </div>
      <div ref={ref} className={heightClass} />
    </div>
  );
}