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

const formatOptions = (data: any) => {
  const currentMonthRate = data.currentMonthRate.sort((a, b) => b.period - a.period);
  const beforeMonthRate = data.beforeMonthRate.sort((a, b) => b.period - a.period);
  const option = {
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    },
    yAxis: {
      type: 'value',
    },
    legend: {
      show: true,
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}月  {c}%',
    },
    series: [
      {
        name: '当年',
        data: currentMonthRate.map((v) => v.val),
        type: 'line',
        label: {
          show: true,
          position: 'top',
          color: '#333',
        },
        smooth: true,
      },
      {
        name: '上一年',
        data: beforeMonthRate.map((v) => v.val),
        type: 'line',
        label: {
          show: true,
          position: 'top',
          color: '#333',
        },
        smooth: true,
      },
    ],
  };
  return option;
};

const MonthRateChart: React.FC<{ data: any }> = ({ 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 MonthRateChart;
