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

const ChartLine = ({ activeReportTab, reportsData, timeRange }) => {
  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]);
    };

    // Define series names and keys dynamically
    let seriesOneName = '';
    let seriesTwoName = '';
    let seriesOneKey = '';
    let seriesTwoKey = '';

    switch (activeReportTab) {
      case 'total_discount_coupons':
        seriesOneName = translate('discount_with_referral_coupon');
        seriesTwoName = translate('total_discount');
        seriesOneKey = 'total_discount_with_referral';
        seriesTwoKey = 'total_discount';
        break;

      case 'total_sales_coupons':
        seriesOneName = translate('sales_with_referral_coupon');
        seriesTwoName = translate('total_sales');
        seriesOneKey = 'total_sales_with_referral';
        seriesTwoKey = 'total_sales';
        break;

      default:
        console.warn('Invalid activeReportTab value:', activeReportTab);
        return;
    }

    // Process chart data
    const chartData = reportsData.chart_data || [];
    if (!chartData.length) {
      console.warn('No chart data available.');
      return;
    }

    const monthShortNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

    let xAxisData = [];
    if (timeRange === 'echo_range_year') {
      xAxisData = chartData.map((item) => {
        const [, month] = item.order_date.split('-');
        return getTranslatedMonthName(parseInt(month, 10) - 1, true);
      });
    } else {
      xAxisData = chartData.map((item) => item.order_date);
    }

    const seriesOneData = chartData.map((item) => parseFloat(item[seriesOneKey] || 0));
    const seriesTwoData = chartData.map((item) => parseFloat(item[seriesTwoKey] || 0));

    const maxLabels = 15;
    const interval = Math.ceil(xAxisData.length / maxLabels);

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

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

          if (timeRange === 'echo_range_year') {
             // Find original index by comparing translated short names (not ideal but works if unique)
             // Alternatively, pass the original index/data through
             const monthIndex = chartData.findIndex((item, idx) => {
                const [, m] = item.order_date.split('-');
                return getTranslatedMonthName(parseInt(m, 10) - 1, true) === axisValue;
             });
             if (monthIndex >= 0) {
                const [, m] = chartData[monthIndex].order_date.split('-');
                fullLabel = getTranslatedMonthName(parseInt(m, 10) - 1, false);
             }
          }

          let content = `<strong>${fullLabel}</strong><br>`;
          params.forEach((item) => {
            content += `
              <span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:${item.color};"></span>
              ${item.seriesName}: <strong>${item.value}</strong><br>
            `;
          });
          return content;
        }
      },
      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: seriesOneName,
          type: 'line',
          smooth: true,
          data: seriesOneData,
        },
        {
          name: seriesTwoName,
          type: 'line',
          smooth: true,
          data: seriesTwoData,
        },
      ],
    };

    myChart.setOption(option);

    // Handle resize
    const handleResize = () => myChart.resize();
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      myChart.dispose();
    };
  }, [activeReportTab, reportsData, timeRange]);

  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 ChartLine;
