import React, { useEffect, useRef, useImperativeHandle, forwardRef } from 'react';
import * as echarts from 'echarts';
import type { EChartsType, EChartsOption } from 'echarts';
import { StockChart as StockChartLib } from '../lib/index';
import type { StockData, DateMemo, TradeRecord, ActiveType } from '../types/index';
import { ChartDrawingTools } from '../lib/drawing/ChartDrawingTools';

// 将 StockChartRef 接口移到 Props 定义之前
interface StockChartRef {
  toggleMemoVisibility: (visible: boolean) => void;
  startDrawing: (type: ActiveType) => void;
  stopDrawing: () => void;
  clearDrawings: () => void;
}

interface StockChartProps {
  stockData: StockData[];
  memoData?: DateMemo[];
  width?: string | number;
  height?: string | number;
  className?: string;
  onChartReady?: (chart: EChartsType) => void;
  trades?: TradeRecord[];
}

// 添加自定义类型定义
interface ScatterDataItemOption {
  value: [number, number];
  symbol?: string;
  symbolSize?: number;
  symbolRotate?: number;
  label?: {
    show?: boolean;
    formatter?: string;
    position?: 'top' | 'bottom' | 'left' | 'right';
    backgroundColor?: string;
    borderColor?: string;
    color?: string;
    padding?: number;
    borderRadius?: number;
    shadowBlur?: number;
    shadowColor?: string;
  };
  itemStyle?: {
    color?: string;
  };
}

// 修改组件定义为 forwardRef，添加解构参数的类型
const StockChart = forwardRef<StockChartRef, StockChartProps>((
  props: StockChartProps, 
  ref: React.ForwardedRef<StockChartRef>
) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstanceRef = useRef<EChartsType | null>(null);
  const stockChartRef = useRef<StockChartLib | null>(null);
  const drawingToolsRef = useRef<ChartDrawingTools | null>(null);

  // 初始化图表和工具 - 只执行一次
  useEffect(() => {
    if (!chartRef.current) return;

    const chartInstance = echarts.init(chartRef.current);
    chartInstanceRef.current = chartInstance;
    
    // 创建 StockChart 实例
    const stockChart = new StockChartLib(props.stockData, props.memoData, chartInstance);
    stockChartRef.current = stockChart;

    // 初始化画线工具 - 只初始化一次
    drawingToolsRef.current = new ChartDrawingTools(chartInstance);

    // 设置初始配置
    const option = stockChart.createChartOption();
    chartInstance.setOption(option as EChartsOption);

    // 在设置完图表配置后初始化绘图工具
    // stockChart.initDrawingTools();

    // // 绑定鼠标事件
    // const zr = chartInstance.getZr();
    // zr.on('click', (params: any) => {
    //   stockChart.handleMouseEvent('click', params);
    // });

    // zr.on('mousedown', (params: any) => {
    //   stockChart.handleMouseEvent('mousedown', params);
    // });

    // zr.on('mousemove', (params: any) => {
    //   stockChart.handleMouseEvent('mousemove', params);
    // });

    // 通知外部图表已准备就绪
    props.onChartReady?.(chartInstance);

    // 清理函数
    return () => {
      // zr.off('click');
      // zr.off('mousedown');
      // zr.off('mousemove');
      chartInstance.dispose();
    };
  }, []); // 空依赖数组，只执行一次

  // 处理数据更新
  useEffect(() => {
    if (!chartRef.current || !chartInstanceRef.current || !stockChartRef.current) return;
    
    const chartInstance = chartInstanceRef.current;
    const stockChart = stockChartRef.current;
    
    // 更新 StockChart 实例的数据
    stockChart.updateData(props.stockData, props.memoData);
    
    // 更新图表数据
    const option = stockChart.createChartOption();
    // console.log('option', option);
    // if (!option) return;

    // 保持原有的 markLine 数据
    const currentOption = chartInstance.getOption() as EChartsOption;
    
    if (currentOption && currentOption.series && Array.isArray(currentOption.series)) {
      const series = currentOption.series as echarts.SeriesOption[];
      const existingMarkLine = series[0] && (series[0] as any).markLine;
      if (existingMarkLine) {
        (option.series[0] as any).markLine = existingMarkLine;
      }
    }

    chartInstance.setOption(option);
    // console.log('currentOption', chartInstance.getOption());
    // 重新绘制所有线条
    drawingToolsRef.current?.redrawLines();
  }, [props.stockData, props.memoData]);

  // 处理窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      chartInstanceRef.current?.resize();
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // 将 toggleMemoVisibility 方法暴露给父组件
  useImperativeHandle(ref, () => ({
    toggleMemoVisibility: (visible: boolean) => {
      if (!stockChartRef.current || !chartInstanceRef.current) return;

      const currentOption = chartInstanceRef.current.getOption();
      const stockChart = stockChartRef.current;

      stockChart.toggleMemoVisibility(visible);
      stockChart.updateMemoVisibility({
        ...currentOption,
        series: currentOption.series
      });
      chartInstanceRef.current.setOption(currentOption);
    },
    startDrawing: (type: ActiveType) => {
      drawingToolsRef.current?.startDrawing(type);
    },
    stopDrawing: () => {
      drawingToolsRef.current?.stopDrawing();
    },
    clearDrawings: () => {
      drawingToolsRef.current?.clearAllLines();
    }
  }));

  // 添加交易标记渲染
  useEffect(() => {
    if (!chartInstanceRef.current || !stockChartRef.current || !props.trades?.length) return;
    
    const tradeMarkSeries: echarts.ScatterSeriesOption = {
      name: "Mark",
      type: "scatter",
      xAxisIndex: 0,
      yAxisIndex: 0,
      data: props.trades.map((trade: TradeRecord, index: number) => {
        const dataIndex = props.stockData.findIndex((data: StockData) => data.d === trade.date);
        if (dataIndex === -1) return null;

        const dayData = props.stockData[dataIndex];
        const price = trade.type === 'BUY' 
          ? parseFloat(dayData.h)
          : parseFloat(dayData.l);

        return {
          value: [dataIndex, price],
          symbol: "triangle",
          symbolSize: 10,
          symbolRotate: trade.type === 'BUY' ? 180 : 0,
          label: {
            show: true,
            formatter: trade.type === 'BUY' ? 'B' : 'S',
            position: trade.type === 'BUY' ? 'top' : 'bottom',
            backgroundColor: '#FFA500',
            borderColor: '#ffffff',
            color: '#ffffff',
            padding: 2,
            borderRadius: 2,
            shadowBlur: 2,
            shadowColor: '#333',
          },
          itemStyle: {
            color: trade.type === 'BUY' ? '#00da3c' : '#ec0000',
          }
        } as ScatterDataItemOption;
      }).filter((item: unknown): item is ScatterDataItemOption => item !== null),
      tooltip: {
        show: false
      }
    };

    const currentOption = chartInstanceRef.current.getOption();
    
    // 找到并移除旧的 Mark 系列（如果存在）
    const markSeriesIndex = currentOption.series.findIndex((s: { name?: string }) => s.name === 'Mark');
    if (markSeriesIndex > -1) {
      currentOption.series.splice(markSeriesIndex, 1);
    }
    
    (currentOption.series as echarts.SeriesOption[]).push(tradeMarkSeries);
    
    chartInstanceRef.current.setOption(currentOption);
  }, [props.trades, props.stockData]);

  return (
    <div
      ref={chartRef}
      style={{ width: "100%", height: "100%" }}
      className={props.className}
    />
  );
});

// 添加显示名称
StockChart.displayName = 'StockChart';

// 导出组件和相关类型，移除重复的 StockChartRef 导出
export default StockChart;
export type { StockChartRef, StockChartProps };
