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

const formatOptions = (data: any) => {
  const currentChartResultList = data.currentChartResultList.sort((a, b) => a.period - b.period);
  const beforeYearChartResultList = data.beforeYearChartResultList.sort(
    (a, b) => a.period - b.period,
  );
  const option = {
    tooltip: {
      trigger: 'axis',
      valueFormatter: (v) => v + '%',
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    },
    legend: {
      show: true,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '去年',
        data: beforeYearChartResultList.map((v) => v.val),
        type: 'line',
        smooth: true,
      },
      {
        name: '今年',
        data: currentChartResultList.map((v) => v.val),
        type: 'line',
        smooth: true,
      },
    ],
  };
  return option;
};

const PassingRateChart: React.FC<{ data: KANBAN.ProductionComprehens.PassRateTrendChart[] }> = ({
  data,
}) => {
  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 chart = getInstanceByDom(chartRef.current);
      const option = formatOptions(data);
      chart?.setOption(option);
    }
  }, [data]);

  return <div ref={chartRef} style={{ height: '500px' }} />;
};

export default PassingRateChart;
