import { useEffect, useRef, useState, useMemo } from "react";
import {
  createChart,
  AreaSeries,
  type IChartApi,
  type ISeriesApi,
  type LineData,
  type Time,
} from "lightweight-charts";

export interface EquityPoint {
  time: string; // YYYY-MM-DD format
  value: number;
}

type TimeRange = "1D" | "1W" | "1M" | "3M" | "1Y" | "ALL";

interface EquityCurveChartProps {
  data: EquityPoint[];
  symbol?: string;
  height?: number;
}

const timeRangeConfig: Record<TimeRange, { label: string; days: number }> = {
  "1D": { label: "1D", days: 1 },
  "1W": { label: "1W", days: 7 },
  "1M": { label: "1M", days: 30 },
  "3M": { label: "3M", days: 90 },
  "1Y": { label: "1Y", days: 365 },
  ALL: { label: "ALL", days: Infinity },
};

export function EquityCurveChart({
  data,
  symbol,
  height = 400,
}: EquityCurveChartProps) {
  const chartContainerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<IChartApi | null>(null);
  const seriesRef = useRef<ISeriesApi<"Area"> | null>(null);
  const [selectedRange, setSelectedRange] = useState<TimeRange>("1M");

  // Filter data based on selected time range
  const filteredData = useMemo(() => {
    if (selectedRange === "ALL") return data;

    const days = timeRangeConfig[selectedRange].days;
    const cutoffDate = new Date();
    cutoffDate.setDate(cutoffDate.getDate() - days);

    return data.filter((point) => new Date(point.time) >= cutoffDate);
  }, [data, selectedRange]);

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

    const chart = createChart(chartContainerRef.current, {
      layout: {
        background: { color: "#0f1419" },
        textColor: "#94a3b8",
        fontFamily:
          'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
      },
      grid: {
        vertLines: {
          color: "#1a2332",
          style: 1,
        },
        horzLines: {
          color: "#1a2332",
          style: 1,
        },
      },
      crosshair: {
        mode: 1,
        vertLine: {
          color: "#00d4aa",
          width: 1,
          style: 2,
          labelBackgroundColor: "#00d4aa",
        },
        horzLine: {
          color: "#00d4aa",
          width: 1,
          style: 2,
          labelBackgroundColor: "#00d4aa",
        },
      },
      rightPriceScale: {
        borderColor: "#1a2332",
        scaleMargins: {
          top: 0.1,
          bottom: 0.1,
        },
      },
      timeScale: {
        borderColor: "#1a2332",
        timeVisible: false,
        secondsVisible: false,
      },
      handleScroll: {
        vertTouchDrag: false,
      },
      handleScale: {
        axisPressedMouseMove: false,
      },
    });

    chartRef.current = chart;

    // Create area series with gradient
    const areaSeries = chart.addSeries(AreaSeries, {
      lineColor: "#00d4aa",
      topColor: "rgba(0, 212, 170, 0.4)",
      bottomColor: "rgba(0, 212, 170, 0.05)",
      lineWidth: 2,
      lastValueVisible: true,
      priceLineVisible: true,
      priceLineColor: "#00d4aa",
      priceLineWidth: 1,
      priceLineStyle: 2,
    });

    seriesRef.current = areaSeries;

    // Handle resize
    const handleResize = () => {
      if (chartContainerRef.current && chartRef.current) {
        const { width } = chartContainerRef.current.getBoundingClientRect();
        chartRef.current.applyOptions({ width });
      }
    };

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

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

  // Update data when filtered data changes
  useEffect(() => {
    if (!seriesRef.current) return;

    const lineData: LineData[] = filteredData.map((point) => ({
      time: point.time as Time,
      value: point.value,
    }));

    seriesRef.current.setData(lineData);

    // Fit content
    if (chartRef.current) {
      chartRef.current.timeScale().fitContent();
    }
  }, [filteredData]);

  // Calculate stats
  const stats = useMemo(() => {
    if (filteredData.length === 0) {
      return { current: 0, high: 0, low: 0, change: 0, changePercent: 0 };
    }

    const values = filteredData.map((d) => d.value);
    const current = values[values.length - 1];
    const high = Math.max(...values);
    const low = Math.min(...values);
    const start = values[0];
    const change = current - start;
    const changePercent = start !== 0 ? (change / start) * 100 : 0;

    return { current, high, low, change, changePercent };
  }, [filteredData]);

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
      minimumFractionDigits: 2,
    }).format(value);
  };

  return (
    <div
      style={{
        backgroundColor: "#0f1419",
        borderRadius: "8px",
        border: "1px solid #1a2332",
        padding: "16px",
      }}
    >
      {/* Header */}
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "flex-start",
          marginBottom: "16px",
        }}
      >
        <div>
          <h3
            style={{
              margin: 0,
              fontSize: "16px",
              fontWeight: 600,
              color: "#e2e8f0",
            }}
          >
            权益曲线
            {symbol && (
              <span style={{ color: "#64748b", marginLeft: "8px" }}>
                ({symbol})
              </span>
            )}
          </h3>
          <div
            style={{
              display: "flex",
              alignItems: "baseline",
              gap: "12px",
              marginTop: "8px",
            }}
          >
            <span
              style={{
                fontSize: "24px",
                fontWeight: 700,
                color: "#e2e8f0",
              }}
            >
              {formatCurrency(stats.current)}
            </span>
            <span
              style={{
                fontSize: "14px",
                fontWeight: 500,
                color: stats.change >= 0 ? "#00d4aa" : "#ef4444",
              }}
            >
              {stats.change >= 0 ? "+" : ""}
              {formatCurrency(stats.change)} (
              {stats.changePercent >= 0 ? "+" : ""}
              {stats.changePercent.toFixed(2)}%)
            </span>
          </div>
        </div>

        {/* Time Range Selector */}
        <div
          style={{
            display: "flex",
            gap: "4px",
            backgroundColor: "#1a2332",
            padding: "4px",
            borderRadius: "6px",
          }}
        >
          {(Object.keys(timeRangeConfig) as TimeRange[]).map((range) => (
            <button
              key={range}
              onClick={() => setSelectedRange(range)}
              style={{
                padding: "6px 12px",
                borderRadius: "4px",
                border: "none",
                backgroundColor:
                  selectedRange === range ? "#0f1419" : "transparent",
                color: selectedRange === range ? "#00d4aa" : "#94a3b8",
                fontSize: "12px",
                fontWeight: 600,
                cursor: "pointer",
                transition: "all 0.15s ease",
              }}
            >
              {timeRangeConfig[range].label}
            </button>
          ))}
        </div>
      </div>

      {/* Stats Row */}
      <div
        style={{
          display: "flex",
          gap: "24px",
          marginBottom: "16px",
          padding: "12px 16px",
          backgroundColor: "#1a2332",
          borderRadius: "6px",
        }}
      >
        <div>
          <div
            style={{ fontSize: "11px", color: "#64748b", marginBottom: "2px" }}
          >
            最高
          </div>
          <div style={{ fontSize: "14px", fontWeight: 600, color: "#00d4aa" }}>
            {formatCurrency(stats.high)}
          </div>
        </div>
        <div>
          <div
            style={{ fontSize: "11px", color: "#64748b", marginBottom: "2px" }}
          >
            最低
          </div>
          <div style={{ fontSize: "14px", fontWeight: 600, color: "#ef4444" }}>
            {formatCurrency(stats.low)}
          </div>
        </div>
        <div>
          <div
            style={{ fontSize: "11px", color: "#64748b", marginBottom: "2px" }}
          >
            数据点
          </div>
          <div style={{ fontSize: "14px", fontWeight: 600, color: "#e2e8f0" }}>
            {filteredData.length}
          </div>
        </div>
      </div>

      {/* Chart Container */}
      <div ref={chartContainerRef} style={{ height: `${height}px` }} />
    </div>
  );
}

// Generate mock equity curve data
export function generateMockEquityData(days: number = 180): EquityPoint[] {
  const data: EquityPoint[] = [];
  const startDate = new Date();
  startDate.setDate(startDate.getDate() - days);

  let equity = 10000;

  for (let i = 0; i < days; i++) {
    const date = new Date(startDate);
    date.setDate(date.getDate() + i);

    // Skip weekends
    if (date.getDay() === 0 || date.getDay() === 6) continue;

    // Random daily change between -2% and +3%
    const change = (Math.random() - 0.4) * 0.05;
    equity = equity * (1 + change);

    data.push({
      time: date.toISOString().split("T")[0],
      value: Math.round(equity * 100) / 100,
    });
  }

  return data;
}

export default EquityCurveChart;
