import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts/core';
export type EChartsOption = Record<string, unknown>;
import { BarChart, CustomChart, LineChart, PieChart } from 'echarts/charts';
import {
  DataZoomComponent,
  GridComponent,
  LegendComponent,
  TooltipComponent,
  VisualMapComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([
  BarChart,
  CustomChart,
  LineChart,
  PieChart,
  DataZoomComponent,
  GridComponent,
  LegendComponent,
  TooltipComponent,
  VisualMapComponent,
  CanvasRenderer,
]);

interface EChartsProps {
  option: EChartsOption;
  style?: React.CSSProperties;
  className?: string;
}

const ECharts: React.FC<EChartsProps> = ({ option, style, className }) => {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!containerRef.current) return;
    const chart = echarts.init(containerRef.current);
    chart.setOption(option);
    const observer = new ResizeObserver(() => chart.resize());
    observer.observe(containerRef.current);
    return () => {
      observer.disconnect();
      chart.dispose();
    };
  }, []);

  useEffect(() => {
    const chart = containerRef.current ? echarts.getInstanceByDom(containerRef.current) : undefined;
    chart?.setOption(option, true);
  }, [option]);

  return <div ref={containerRef} className={className} style={style} />;
};

export default ECharts;
