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 "pages/api/api";
// chart options

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

const SalesChart = () => {
  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;
  const {
    isLoading: isLoadingDeliveryInsight,
    isError: isErrorDeliveryInsight, //true or false
    data: orderInsightdata,
    error: deliveryInsightError,
  } = useQuery({
    queryKey: ["deliveryInsight"],
    queryFn: fetchDeliveryInsight,
  });

  const [series, setSeries] = useState([]);
  useEffect(() => {
    if (orderInsightdata && orderInsightdata.length > 0) {
      const newSeries = orderInsightdata.map((zone) => ({
        name: zone.locationname,
        // data: Object.values(zone.ordermonths[0]).slice(0, -1), // Extracting month values
        data: Object.values(zone.ordermonths),
      }));

      setSeries(newSeries);
      console.log("newSeries", newSeries);
    }
  }, [orderInsightdata]);

  // const [series] = useState([
  //   {
  //     name: "Net Profit",
  //     data: [94, 55, 57, 56, 61, 58, 63, 60, 66, 22, 22, 22],
  //   },
  //   {
  //     name: "Re",
  //     data: [76, 85, 101, 98, 87, 105, 91, 114, 94],
  //   },
  //   {
  //     name: "Free Cash Flow",
  //     data: [35, 41, 36, 26, 45, 48, 52, 53, 41],
  //   },
  // ]);

  const columnChartOptions = {
    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: [
        "Jan",
        "Feb",
        "Mar",
        "Apr",
        "May",
        "Jun",
        "Jul",
        "Aug",
        "Sep",
        "Oct",
        "Nov",
        "Dec",
      ],
    },
    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 [options, setOptions] = useState(columnChartOptions);

  useEffect(() => {
    setOptions((prevState) => ({
      ...prevState,
      colors: [secondary, primaryMain, successDark],
      xaxis: {
        labels: {
          style: {
            colors: [
              primary,
              primary,
              primary,
              primary,
              primary,
              primary,
              primary,
              primary,
              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) return <Loader />;

  if (isErrorDeliveryInsight)
    return (
      "An error has occurred:(isErrorDeliveryInsight) " +
      deliveryInsightError.message
    );

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

export default SalesChart;
