import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import { translate } from '../Helper';

const ChartBar = ({ timeRange, reportsData }) => {
  const chartRef = useRef(null);

  useEffect(() => {
    // Helper to get translated month names
    const getTranslatedMonthName = (index, short = true) => {
      const monthShortNames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
      const monthFullNames = [
        'january', 'february', 'march', 'april', 'may', 'june',
        'july', 'august', 'september', 'october', 'november', 'december'
      ];
      return short ? translate(monthShortNames[index]) : translate(monthFullNames[index]);
    };

    if (!reportsData || !reportsData.chart_data || reportsData.chart_data.length === 0) {
      console.warn('No chart data available.');
      return;
    }

    const chartData = reportsData.chart_data;

    // Process data for the chart
    let xAxisData = [];
    let seriesData = [];

    if (timeRange === 'echo_range_year') {
      // Group data by month for yearly range
      const monthlyData = {};
      const monthShortNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

      chartData.forEach(item => {
        const [, month] = item.order_date.split('-');
        const monthIndex = parseInt(month, 10) - 1;
        const monthName = getTranslatedMonthName(monthIndex, true);
        monthlyData[monthName] = (monthlyData[monthName] || 0) + parseInt(item.referral_order_count || 0);
      });

      xAxisData = Object.keys(monthlyData);
      seriesData = Object.values(monthlyData);
    } else {
      // Use raw dates for other time ranges
      xAxisData = chartData.map(item => item.order_date);
      seriesData = chartData.map(item => parseInt(item.referral_order_count || 0));
    }

    // Calculate label interval for better visibility
    const maxLabels = 15;
    const interval = Math.ceil(xAxisData.length / maxLabels);

    // Initialize chart
    const chartDom = chartRef.current;
    const myChart = echarts.init(chartDom);

    const option = {
      color: ['#0080FF'],
      legend: {
        bottom: '0',
        itemWidth: 14,
      },
      grid: {
        top: '30px',
        bottom: '100px',
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          let axisValue = params[0].axisValue;
          let fullLabel = axisValue;

          // If yearly range, expand and translate month names
          if (timeRange === 'echo_range_year') {
            const shortMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
            const originalMonthIndex = shortMonthNames.findIndex(name => {
              const idx = shortMonthNames.indexOf(name);
              return getTranslatedMonthName(idx, true) === axisValue;
            });

            if (originalMonthIndex >= 0) {
              fullLabel = getTranslatedMonthName(originalMonthIndex, false); // Get translated full name
            }
          }

          return `
            <strong>${fullLabel}</strong><br>
            ${params[0].marker} ${params[0].seriesName}: <strong>${params[0].value}</strong>
          `;
        },
      },
      xAxis: {
        type: 'category',
        data: xAxisData,
        axisTick: { show: false },
        axisLine: { show: false },
        axisLabel: {
          interval: interval - 1,
          rotate: 45,
        },
      },
      yAxis: {
        type: 'value',
        axisLine: { show: false },
      },
      series: [
        {
          name: translate('referral_orders'),
          type: 'bar',
          data: seriesData,
          barWidth: '50%',
        },
      ],
    };

    myChart.setOption(option);

    // Resize chart on window resize
    const handleResize = () => {
      myChart.resize();
    };
    window.addEventListener('resize', handleResize);

    // Clean up on component unmount
    return () => {
      window.removeEventListener('resize', handleResize);
      myChart.dispose();
    };
  }, [timeRange, reportsData]);

  return (
    <div className="ecre-bg-white ecre-rounded-lg ecre-pb-4">
      <div ref={chartRef} className="ecre-w-full ecre-h-[400px] sm:ecre-h-[500px]"></div>
    </div>
  );
};

export default ChartBar;
