import * as echarts from 'echarts/lib/echarts';
import type { ECharts } from 'echarts';
import { getInstanceByDom } from 'echarts';
import { useEffect, useRef } from 'react';

type PropParams = {
  title: string;
  data: KANBAN.AirBottleProcessKanban.ChartDataDto[];
  color?: string;
};

const OutputChart: React.FC<PropParams> = ({ title, data, color }) => {
  const chartRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Initialize chart
    let chart: ECharts | undefined;
    if (chartRef.current !== null) {
      chart = echarts.init(chartRef.current);
    }

    // Add chart resize listener
    // ResizeObserver is leading to a bit janky UX
    function resizeChart() {
      chart?.resize();
    }
    window.addEventListener('resize', resizeChart);

    // Return cleanup function
    return () => {
      chart?.dispose();
      window.removeEventListener('resize', resizeChart);
    };
  }, []);

  useEffect(() => {
    if (chartRef.current !== null) {
      const chartData = data.sort((a, b) => a.period - b.period);
      const chart = getInstanceByDom(chartRef.current);
      const option = {
        title: {
          text: title,
          textStyle: {
            color: '#fff',
            fontSize: 18,
          },
          top: 10,
          left: 10,
        },
        color: ['#f2c042', '#00ff00'],
        grid: {
          bottom: 30,
          top: 60,
          left: 50,
          right: 30,
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 10,
          textStyle: {
            color: '#fff',
          },
        },
        xAxis: {
          type: 'category',
          splitLine: false,
          boundaryGap: false,
          data: chartData.map((item) => item.period),
        },
        yAxis: {
          type: 'value',
          splitLine: false,
          //max: Math.max(...chartData.map((item) => item.val)) * 2
        },
        series: [
          {
            name: '计划产量',
            type: 'line',
            symbol: 'none',
            data: chartData.map((item) => item.val),
          },
          {
            name: '实际产量',
            type: 'line',
            stack: 'Total',
            symbol: 'emptyRect',
            symbolSize: 3,
            smooth: true,
            data: chartData.map((item) => item.val2),
          },
        ],
      };
      chart?.setOption(option);
    }
  }, [title, data]);
  return <div className="chart" ref={chartRef} style={{ width: '100%', height: '100%' }}></div>;
};

export default OutputChart;
