import { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import type { KLineData, MACDData } from '@/types';

interface KLineChartProps {
  klineData: KLineData[];
  macdData: MACDData[];
  resistance: number[];
  support: number[];
  height?: number;
}

export function KLineChart({ klineData, macdData, resistance, support, height = 500 }: KLineChartProps) {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!chartRef.current || klineData.length === 0) return;

    // 初始化图表
    if (!chartInstance.current) {
      chartInstance.current = echarts.init(chartRef.current);
    }

    const chart = chartInstance.current;

    // 处理数据
    const dates = klineData.map(d => {
      const date = new Date(d.time);
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    });
    
    const klineValues = klineData.map(d => [d.open, d.close, d.low, d.high]);
    const volumes = klineData.map(d => d.volume);
    
    // MACD数据
    const difData = macdData.map(d => d.dif);
    const deaData = macdData.map(d => d.dea);
    const macdBarData = macdData.map(d => ({
      value: d.macd,
      itemStyle: {
        color: d.macd >= 0 ? '#7dd75a' : '#ef4444',
      },
    }));

    // 生成关键点位线
    const markLines: any[] = [];
    
    // 压力位
    resistance.forEach((price, index) => {
      markLines.push({
        yAxis: price,
        name: `压力${index + 1}`,
        lineStyle: {
          color: '#ef4444',
          type: 'solid',
          width: 1.5,
        },
        label: {
          formatter: `压力{${index + 1}}: {c}`,
          color: '#ef4444',
          fontSize: 11,
        },
      });
    });
    
    // 支撑位
    support.forEach((price, index) => {
      markLines.push({
        yAxis: price,
        name: `支撑${index + 1}`,
        lineStyle: {
          color: '#7dd75a',
          type: 'solid',
          width: 1.5,
        },
        label: {
          formatter: `支撑{${index + 1}}: {c}`,
          color: '#7dd75a',
          fontSize: 11,
        },
      });
    });

    // 计算MA
    const calculateMA = (dayCount: number) => {
      const result: number[] = [];
      for (let i = 0; i < klineData.length; i++) {
        if (i < dayCount - 1) {
          result.push(Number(klineData[i].close.toFixed(2)));
          continue;
        }
        let sum = 0;
        for (let j = 0; j < dayCount; j++) {
          sum += klineData[i - j].close;
        }
        result.push(Number((sum / dayCount).toFixed(2)));
      }
      return result;
    };

    const ma5 = calculateMA(5);
    const ma10 = calculateMA(10);
    const ma20 = calculateMA(20);

    const option: echarts.EChartsOption = {
      backgroundColor: 'transparent',
      animation: true,
      animationDuration: 500,
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#0d5d1b',
          },
        },
        backgroundColor: 'rgba(9, 9, 11, 0.95)',
        borderColor: '#7dd75a',
        borderWidth: 1,
        textStyle: {
          color: '#fff',
          fontSize: 12,
        },
        formatter: (params: any) => {
          const kline = params.find((p: any) => p.seriesName === 'K线');
          const vol = params.find((p: any) => p.seriesName === '成交量');
          const macd = params.find((p: any) => p.seriesName === 'MACD');
          
          if (!kline) return '';
          
          const data = kline.data;
          const open = data[1];
          const close = data[2];
          const low = data[3];
          const high = data[4];
          const change = ((close - open) / open * 100).toFixed(2);
          const changeColor = close >= open ? '#7dd75a' : '#ef4444';
          
          return `
            <div style="padding: 8px;">
              <div style="font-weight: bold; margin-bottom: 8px; color: #e6e6e6;">${kline.axisValue}</div>
              <div style="display: grid; grid-template-columns: auto auto; gap: 4px 16px; font-size: 12px;">
                <span style="color: #a1a1aa;">开盘:</span><span style="color: #fff;">${open.toFixed(2)}</span>
                <span style="color: #a1a1aa;">最高:</span><span style="color: #fff;">${high.toFixed(2)}</span>
                <span style="color: #a1a1aa;">最低:</span><span style="color: #fff;">${low.toFixed(2)}</span>
                <span style="color: #a1a1aa;">收盘:</span><span style="color: ${changeColor};">${close.toFixed(2)} (${change}%)</span>
                ${vol ? `<span style="color: #a1a1aa;">成交量:</span><span style="color: #fff;">${vol.data.toLocaleString()}</span>` : ''}
                ${macd ? `<span style="color: #a1a1aa;">MACD:</span><span style="color: ${macd.data >= 0 ? '#7dd75a' : '#ef4444'};">${macd.data.toFixed(4)}</span>` : ''}
              </div>
            </div>
          `;
        },
      },
      axisPointer: {
        link: [{ xAxisIndex: 'all' }],
        label: {
          backgroundColor: '#0d5d1b',
        },
      },
      grid: [
        {
          left: '3%',
          right: '3%',
          top: '5%',
          height: '50%',
          containLabel: true,
        },
        {
          left: '3%',
          right: '3%',
          top: '58%',
          height: '15%',
          containLabel: true,
        },
        {
          left: '3%',
          right: '3%',
          top: '76%',
          height: '18%',
          containLabel: true,
        },
      ],
      xAxis: [
        {
          type: 'category',
          data: dates,
          boundaryGap: true,
          axisLine: { lineStyle: { color: '#3f3f46' } },
          axisLabel: { color: '#a1a1aa', fontSize: 10 },
          axisTick: { show: false },
          splitLine: { show: false },
        },
        {
          type: 'category',
          gridIndex: 1,
          data: dates,
          boundaryGap: true,
          axisLine: { show: false },
          axisLabel: { show: false },
          axisTick: { show: false },
          splitLine: { show: false },
        },
        {
          type: 'category',
          gridIndex: 2,
          data: dates,
          boundaryGap: true,
          axisLine: { lineStyle: { color: '#3f3f46' } },
          axisLabel: { color: '#a1a1aa', fontSize: 10 },
          axisTick: { show: false },
          splitLine: { show: false },
        },
      ],
      yAxis: [
        {
          scale: true,
          axisLine: { lineStyle: { color: '#3f3f46' } },
          axisLabel: { color: '#a1a1aa', fontSize: 10 },
          splitLine: { lineStyle: { color: '#27272a', type: 'dashed' } },
          position: 'right',
        },
        {
          scale: true,
          gridIndex: 1,
          axisLine: { show: false },
          axisLabel: { show: false },
          splitLine: { show: false },
        },
        {
          scale: true,
          gridIndex: 2,
          axisLine: { lineStyle: { color: '#3f3f46' } },
          axisLabel: { color: '#a1a1aa', fontSize: 10 },
          splitLine: { lineStyle: { color: '#27272a', type: 'dashed' } },
          position: 'right',
        },
      ],
      dataZoom: [
        {
          type: 'inside',
          xAxisIndex: [0, 1, 2],
          start: 50,
          end: 100,
        },
        {
          type: 'slider',
          xAxisIndex: [0, 1, 2],
          start: 50,
          end: 100,
          height: 20,
          bottom: 0,
          borderColor: '#3f3f46',
          fillerColor: 'rgba(125, 215, 90, 0.2)',
          handleStyle: { color: '#7dd75a' },
          textStyle: { color: '#a1a1aa' },
        },
      ],
      series: [
        {
          name: 'K线',
          type: 'candlestick',
          data: klineValues,
          itemStyle: {
            color: '#7dd75a',
            color0: '#ef4444',
            borderColor: '#7dd75a',
            borderColor0: '#ef4444',
          },
          markLine: {
            symbol: 'none',
            data: markLines,
            animation: true,
          },
        },
        {
          name: 'MA5',
          type: 'line',
          data: ma5,
          smooth: true,
          showSymbol: false,
          lineStyle: { color: '#fbbf24', width: 1 },
        },
        {
          name: 'MA10',
          type: 'line',
          data: ma10,
          smooth: true,
          showSymbol: false,
          lineStyle: { color: '#60a5fa', width: 1 },
        },
        {
          name: 'MA20',
          type: 'line',
          data: ma20,
          smooth: true,
          showSymbol: false,
          lineStyle: { color: '#c084fc', width: 1 },
        },
        {
          name: '成交量',
          type: 'bar',
          xAxisIndex: 1,
          yAxisIndex: 1,
          data: volumes,
          itemStyle: {
            color: (params: any) => {
              const index = params.dataIndex;
              const close = klineData[index]?.close;
              const open = klineData[index]?.open;
              return close >= open ? 'rgba(125, 215, 90, 0.6)' : 'rgba(239, 68, 68, 0.6)';
            },
          },
        },
        {
          name: 'MACD',
          type: 'bar',
          xAxisIndex: 2,
          yAxisIndex: 2,
          data: macdBarData,
        },
        {
          name: 'DIF',
          type: 'line',
          xAxisIndex: 2,
          yAxisIndex: 2,
          data: difData,
          smooth: true,
          showSymbol: false,
          lineStyle: { color: '#fbbf24', width: 1.5 },
        },
        {
          name: 'DEA',
          type: 'line',
          xAxisIndex: 2,
          yAxisIndex: 2,
          data: deaData,
          smooth: true,
          showSymbol: false,
          lineStyle: { color: '#60a5fa', width: 1.5 },
        },
      ],
    };

    chart.setOption(option);
    setLoading(false);

    // 响应式
    const handleResize = () => {
      chart.resize();
    };
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [klineData, macdData, resistance, support]);

  return (
    <div className="relative">
      {loading && (
        <div className="absolute inset-0 flex items-center justify-center bg-[#09090b]/80 z-10">
          <div className="flex items-center gap-2 text-[#7dd75a]">
            <div className="w-5 h-5 border-2 border-[#7dd75a] border-t-transparent rounded-full animate-spin" />
            <span className="text-sm">加载中...</span>
          </div>
        </div>
      )}
      <div ref={chartRef} style={{ height: `${height}px` }} className="w-full" />
    </div>
  );
}
