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

const formatOptions = (data: any) => {
  data.sort((a, b) => a.period - b.period);
  const option = {
    tooltip: {
      trigger: 'axis',
      valueFormatter: (v) => v + '%',
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.map((v) => v.period),
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: data.map((v) => v.val),
        type: 'line',
        smooth: true,
      },
    ],
  };
  return option;
};

const PassingRateChart: React.FC<{ data: KANBAN.QiPingComprehens.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;
