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

const formatOptions = (data: any) => {
  const option = {
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.map((v) => v.period),
    },
    yAxis: {
      type: 'value',
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{c}%',
    },
    series: [
      {
        data: data.map((v) => v.val),
        type: 'line',
        smooth: true,
        label: {
          show: true,
          position: 'top',
          color: '#333',
        },
      },
    ],
  };
  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;
