import { useEffect, useRef } from "react";
import { createChart, ColorType, AreaSeries } from "lightweight-charts";
import type { IChartApi, ISeriesApi, AreaData, Time } from "lightweight-charts";
import type { EquityPoint } from "@/types/models";

interface EquityChartProps {
  data: EquityPoint[];
  height?: number;
}

export function EquityChart({ data, height = 300 }: EquityChartProps) {
  const chartContainerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<IChartApi | null>(null);
  const seriesRef = useRef<ISeriesApi<"Area"> | null>(null);

  useEffect(() => {
    if (!chartContainerRef.current) return;

    const chart = createChart(chartContainerRef.current, {
      layout: {
        background: { type: ColorType.Solid, color: "#1e1e1e" },
        textColor: "#a0a0a0",
        fontFamily: "Inter, sans-serif",
      },
      grid: {
        vertLines: { color: "#2c2c2c" },
        horzLines: { color: "#2c2c2c" },
      },
      rightPriceScale: {
        borderColor: "#2c2c2c",
        scaleMargins: {
          top: 0.1,
          bottom: 0.1,
        },
      },
      timeScale: {
        borderColor: "#2c2c2c",
        timeVisible: true,
      },
      handleScroll: true,
      handleScale: true,
      height,
    });

    const series = chart.addSeries(AreaSeries, {
      lineColor: "#00ffcc",
      topColor: "rgba(0, 255, 204, 0.2)",
      bottomColor: "rgba(0, 255, 204, 0.0)",
      lineWidth: 3,
      priceFormat: {
        type: "price",
        precision: 2,
        minMove: 0.01,
      },
    });

    chartRef.current = chart;
    seriesRef.current = series;

    const handleResize = () => {
      if (chartContainerRef.current && chartRef.current) {
        chartRef.current.applyOptions({
          width: chartContainerRef.current.clientWidth,
        });
      }
    };

    window.addEventListener("resize", handleResize);
    handleResize();

    return () => {
      window.removeEventListener("resize", handleResize);
      chart.remove();
    };
  }, [height]);

  useEffect(() => {
    if (seriesRef.current && data.length > 0) {
      // Sort data by timestamp to avoid Lightweight Charts errors
      const sortedData = [...data].sort(
        (a, b) =>
          new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
      );

      const uniqueDataMap = new Map<number, number>();
      sortedData.forEach((point) => {
        // Group by seconds to avoid duplicate timestamps
        const timeInSeconds = Math.floor(
          new Date(point.timestamp).getTime() / 1000,
        );
        uniqueDataMap.set(timeInSeconds, point.equity);
      });

      const chartData: AreaData[] = Array.from(uniqueDataMap.entries())
        .sort((a, b) => a[0] - b[0])
        .map(([time, value]) => ({
          time: time as Time,
          value,
        }));

      if (chartData.length > 0) {
        seriesRef.current.setData(chartData);
        chartRef.current?.timeScale().fitContent();
      }
    }
  }, [data]);

  return (
    <div className="bg-[#1e1e1e] border border-[#2c2c2c] rounded-xl overflow-hidden">
      <div className="px-4 py-3 border-b border-[#2c2c2c]">
        <h3 className="text-sm font-semibold text-[#e1e1e1]">权益业绩矩阵</h3>
      </div>
      <div className="p-4">
        <div ref={chartContainerRef} className="w-full" />
      </div>
    </div>
  );
}
