import React, { useEffect, useRef } from 'react';
import { memo } from 'react';
import * as echarts from 'echarts';

const BarChart = ({ data, categories, colors, title, className }) => {
    const chartRef = useRef(null);
    const chartInstanceRef = useRef(null);
  
    // Initialize chart once
    useEffect(() => {
      if (!chartRef.current) return;
      
      chartInstanceRef.current = echarts.init(chartRef.current);
      
      return () => {
        if (chartInstanceRef.current) {
          chartInstanceRef.current.dispose();
          chartInstanceRef.current = null;
        }
      };
    }, []); // Only run once on mount

    // Update chart data when data/categories/colors/title change
    useEffect(() => {
      if (!chartInstanceRef.current) return;
      
      // Remove the sorting of data and categories
      const chartData = [...data];
      const chartCategories = [...categories];
      
      // Keep colors in their original order to match data
      const chartColors = [...colors];
  
      const options = {
        title: {
          text: title || '',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        grid: {
          top: '10%',
          left: '-22%',
          right: '10%',
          bottom: '13%',
          containLabel: true,
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01],
          axisLabel: {
            formatter: (value) => {
              if (value >= 1000) {
                return `${value / 1000}k`;
              }
              return value;
            },
          },
        },
        yAxis: {
          show: false,    
          type: 'category',
          data: chartCategories,
        },
        series: [
          {
            name: 'Order',
            type: 'bar',
            top: 10,
            left: 10,
            right: 10,
            bottom: 20,
            data: chartData,
            avoidLabelOverlap: false,
            itemStyle: {
              color: (params) => chartColors[params.dataIndex],
              borderRadius: [0, 4, 4, 0],
            },
            barWidth: '60%',
          },
        ],
      };
  
      chartInstanceRef.current.setOption(options);
    }, [data, categories, colors, title]); // Removed className - it doesn't affect chart data

    // Handle resize when className changes (for responsive layouts)
    useEffect(() => {
      if (!chartInstanceRef.current) return;
      
      // Small delay to ensure DOM has updated
      const timer = setTimeout(() => {
        chartInstanceRef.current?.resize();
      }, 0);
      
      return () => clearTimeout(timer);
    }, [className]);

  return (
    <div
      ref={chartRef}
      className={`arcm-bar-chart ${className || 'arcm-h-[170px] arcm-w-[320px]'}`}
    ></div>
  );
};

export default memo(BarChart);