import { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import Loader from 'components/Loader';

// material-ui
import { useTheme } from '@mui/material/styles';
import { Box } from '@mui/material';

// third-party
import ReactApexChart from 'react-apexcharts';

// project import
import { ThemeMode } from 'config';
import useConfig from 'hooks/useConfig';
import { fetchDeliveryInsight } from './api';

// ==============================|| APEXCHART - COLUMN ||============================== //

const DeliveriesSalesChart = () => {
  const theme = useTheme();
  const { mode } = useConfig();
  const { primary } = theme.palette.text;
  const line = theme.palette.divider;
  const grey200 = theme.palette.grey[200];
  const secondary = theme.palette.c_color.main;
  const primaryMain = theme.palette.m_color.main;
  const successDark = theme.palette.n_color.main;

  // ✅ keep local state for series & categories
  const [series, setSeries] = useState([]);
  const [options, setOptions] = useState({
    chart: {
      type: 'bar',
      height: 350
    },
    plotOptions: {
      bar: {
        horizontal: false,
        columnWidth: '35%',
        endingShape: 'rounded'
      }
    },
    dataLabels: {
      enabled: false
    },
    stroke: {
      show: true,
      width: 2,
      colors: ['transparent']
    },
    xaxis: {
      categories: [] // ✅ dynamic from API
    },
    yaxis: {
      title: {
        text: ''
      }
    },
    fill: {
      opacity: 1
    },
    tooltip: {
      y: {
        formatter(val) {
          return ` Deliveries: ${val}`;
        }
      }
    },
    legend: {
      show: true,
      fontFamily: `'Roboto', sans-serif`,
      position: 'bottom',
      offsetX: 10,
      offsetY: 10,
      labels: {
        useSeriesColors: false
      },
      markers: {
        width: 16,
        height: 16,
        radius: 5
      },
      itemMargin: {
        horizontal: 15,
        vertical: 8
      }
    },
    responsive: [
      {
        breakpoint: 600,
        options: {
          yaxis: {
            show: false
          }
        }
      }
    ]
  });

  const {
    isLoading: isLoadingDeliveryInsight,
    isError: isErrorDeliveryInsight,
    data: orderInsightdata,
    error: deliveryInsightError
  } = useQuery({
    queryKey: ['deliveryInsight'],
    queryFn: fetchDeliveryInsight,
    keepPreviousData: true
  });

  useEffect(() => {
    if (orderInsightdata && orderInsightdata.length > 0) {
      // ✅ dynamically take months from API keys
      const categories = Object.keys(orderInsightdata[0].ordermonths);

      const newSeries = orderInsightdata.map((zone) => ({
        name: zone.locationname,
        data: Object.values(zone.ordermonths)
      }));

      setSeries(newSeries);

      // ✅ update chart options with API categories
      setOptions((prev) => ({
        ...prev,
        xaxis: {
          ...prev.xaxis,
          categories: categories
        }
      }));
    }
  }, [orderInsightdata]);

  useEffect(() => {
    // ✅ apply theme changes
    setOptions((prevState) => ({
      ...prevState,
      colors: [secondary, primaryMain, successDark],
      xaxis: {
        ...prevState.xaxis,
        labels: {
          style: {
            colors: Array(prevState.xaxis.categories.length).fill(primary)
          }
        }
      },
      yaxis: {
        labels: {
          style: {
            colors: [primary]
          }
        }
      },
      grid: {
        borderColor: line
      },
      theme: {
        mode: mode === ThemeMode.DARK ? 'dark' : 'light'
      },
      legend: {
        labels: {
          colors: 'grey.500'
        }
      }
    }));
  }, [mode, primary, line, grey200, secondary, primaryMain, successDark]);

  if (isLoadingDeliveryInsight && series.length === 0) {
    return <Loader />;
  }

  if (isErrorDeliveryInsight) {
    return 'An error has occurred: ' + deliveryInsightError.message;
  }

  return (
    <Box id="chart" sx={{ bgcolor: 'transparent' }}>
      <ReactApexChart options={options} series={series} type="bar" height={350} />
    </Box>
  );
};

export default DeliveriesSalesChart;
