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

const formatOptions = (data) => {
  const options = {
    xAxis: {
      type: 'category',
      name: '月份',
      data: data.map((v) => v.period),
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: data.map((v) => v.val),
        type: 'bar',
        label: {
          show: true,
          position: 'top',
          color: '#333',
        },
      },
    ],
  };

  return options;
};

const AnnualPlanBar: 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);
      console.log(option, '0000');
      chart?.setOption(option);
    }
  }, [data]);

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

export default AnnualPlanBar;
