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

type PropParams = {
  title: string;
  data: KANBAN.EvacuationProcessKanban.chartDto[];
  color?: string;
};

const TrendChart: React.FC<PropParams> = ({ title, data, color }) => {
  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 = {
        title: {
          text: title,
          textStyle: {
            color: '#fff',
            fontSize: 18,
          },
        },
        color: color ? [color] : ['#004af2'],
        grid: {
          bottom: 30,
          top: 40,
          left: 50,
          right: 30,
        },
        xAxis: {
          type: 'category',
          splitLine: false,
          boundaryGap: false,
          data: data.map((item) => item.period),
        },
        yAxis: {
          type: 'value',
          splitLine: false,
        },
        series: [
          {
            // name: 'Email',
            type: 'line',
            stack: 'Total',
            symbol: 'emptyRect',
            symbolSize: 4,
            smooth: true,
            data: data.map((item) => item.val),
          },
        ],
      };
      chart?.setOption(option);
    }
  }, [title, data]);
  return (
    <div className="chart" ref={chartRef}>
      chart
    </div>
  );
};

export default TrendChart;
