import React, { useEffect, useState } from "react";
import TitleCard from "pages/titleCard";
import { useTheme } from "@mui/material/styles";
import MainCard from "components/MainCard";
import { Link as RouterLink, useNavigate } from "react-router-dom";
import SalesChart from "./SalesChart";
import LoadingIcons from "react-loading-icons";
import { HiHandThumbDown, HiHandThumbUp } from "react-icons/hi2";
import HoverSocialCard from "components/cards/statistics/HoverSocialCard";
import { ThemeMode } from "config";
import { DashboardOutlined } from "@ant-design/icons";
import axios from "axios";
import {
  Avatar,
  Grid,
  Link,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
} from "@mui/material";
import Loader from "components/Loader";
import { useQuery } from "@tanstack/react-query";

import {
  fetchOrderSummary,
  fetchLocationSummary,
  fetchOrderInsight,
} from "pages/api/api";

const Orders = () => {
  // const chartdata = async () => {
  //   try {
  //     const response = await axios.get(
  //       `${process.env.REACT_APP_URL}/orders/getorderinsight`
  //     );

  //     console.log("chartdata", response);
  //   } catch (err) {
  //     console.log("chartdata", chartdata);
  //   }
  // };
  // useEffect(() => {
  //   chartdata();
  // }, []);

  const [series, setSeries] = useState([]);

  const theme = useTheme();
  const navigate = useNavigate();

  const primary = theme.palette.primary.main;
  /* ============================================= || fetchOrderInsight || ============================================= */

  const {
    isLoading: isLoadingOrderInsight,
    isError: isErrorOrderInsight, //true or false
    data: orderInsightdata,
    error: orderInsightError,
  } = useQuery({
    queryKey: ["orderInsight"],
    queryFn: fetchOrderInsight,
  });

  /* ============================================= || fetchOrderSummary || ============================================= */

  const {
    isLoading: isLoadingOrderSummary,
    isError: isErrorOrderSummary, //true or false
    data: orderSummarydata,
    error: orderSummaryError,
  } = useQuery({
    queryKey: ["orderSummary"],
    queryFn: fetchOrderSummary,
  });

  /* ============================================= || fetchLocationSummary || ============================================= */

  const {
    isLoading: isLoadingLocationSummary,
    isError: isErrorLocationSummary, //true or false
    data: locationSummarydata,
    error: locationSummaryError,
  } = useQuery({
    queryKey: ["locationSummary"],
    queryFn: fetchLocationSummary,
  });

  useEffect(() => {
    if (orderInsightdata && orderInsightdata.length > 0) {
      console.log("orderInsightdata", orderInsightdata);
      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]);

  if (
    isLoadingOrderSummary ||
    isLoadingLocationSummary ||
    isLoadingOrderInsight
  ) {
    return <Loader />;
  }

  if (isErrorOrderSummary) {
    return (
      "An error has occurred:(isErrorOrderSummary) " + orderSummaryError.message
    );
  }
  if (isErrorLocationSummary) {
    return (
      "An error has occurred:(isErrorLocationSummary) " +
      locationSummaryError.message
    );
  }

  if (isErrorOrderInsight) {
    return (
      "An error has occurred:(isErrorOrderInsight) " + orderInsightError.message
    );
  }

  return (
    <>
      <TitleCard title="Orders" />
      {/* ============================================= || Hover Social Card  || ============================================= */}
      <Grid container spacing={3} sx={{ mt: "0px" }}>
        {" "}
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Orders"
            secondary={orderSummarydata.total}
            iconPrimary={DashboardOutlined}
            color={theme.palette.primary.main}
          />
        </Grid>{" "}
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Delivered"
            secondary={orderSummarydata.delivered}
            iconPrimary={HiHandThumbUp}
            color={theme.palette.success.main}
          />
        </Grid>
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Pending"
            secondary={orderSummarydata.pending}
            iconPrimary={LoadingIcons.ThreeDots}
            color={
              theme.palette.mode === ThemeMode.DARK
                ? theme.palette.secondary.lighter
                : theme.palette.warning.main
            }
          />
        </Grid>
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Cancelled"
            secondary={orderSummarydata.cancelled}
            iconPrimary={HiHandThumbDown}
            color={theme.palette.error.main}
          />
        </Grid>
      </Grid>
      <Grid container spacing={3} sx={{ mt: 2 }}>
        {" "}
        {/* ============================================= || left column|| ============================================= */}
        <Grid item xs={12} sm={8}>
          <MainCard
            elevation={0}
            title="Orders Status"
            content={false}
            secondary={
              <Link
                component={RouterLink}
                to="/reports/ordersdetails"
                color="primary"
              >
                View all
              </Link>
            }
          >
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell sx={{ pl: 3 }}>Zones</TableCell>
                    <TableCell sx={{ textAlign: "right" }}>Orders</TableCell>
                    <TableCell sx={{ textAlign: "right" }}>Delivered</TableCell>
                    <TableCell sx={{ textAlign: "right" }}>Pending</TableCell>
                    <TableCell sx={{ textAlign: "right" }}>Cancelled</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {locationSummarydata.map((zone, index) => (
                    <TableRow hover key={index}>
                      <TableCell sx={{ pl: 3, minWidth: 0 }}>
                        <Grid
                          container
                          spacing={1}
                          alignItems="center"
                          wrap="nowrap"
                        >
                          <Grid item>
                            <Avatar
                              sx={{
                                bgcolor:
                                  index === 0
                                    ? theme.palette.c_color.main
                                    : index === 1
                                    ? theme.palette.m_color.main
                                    : theme.palette.n_color.main,
                                width: 36,
                                height: 36,
                                fontSize: 16,
                              }}
                            >
                              {zone.locationname?.charAt(0)}
                            </Avatar>
                          </Grid>
                          <Grid item xs zeroMinWidth>
                            <Typography
                              align="left"
                              variant="subtitle1"
                              noWrap
                              sx={{
                                overflow: "hidden",
                                textOverflow: "ellipsis",
                              }}
                            >
                              {zone.locationname}
                            </Typography>
                          </Grid>
                        </Grid>
                      </TableCell>

                      <TableCell
                        sx={{
                          textAlign: { xs: "left", sm: "right" }, // stack on small screens
                          pt: { xs: 1, sm: 0 },
                          wordBreak: "break-word",
                        }}
                      >
                        {zone.total}
                      </TableCell>

                      <TableCell sx={{ textAlign: "right" }}>
                        {zone.delivered}
                      </TableCell>
                      <TableCell sx={{ textAlign: "right" }}>
                        {zone.pending}
                      </TableCell>
                      <TableCell sx={{ textAlign: "right" }}>
                        {zone.cancelled}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </MainCard>
        </Grid>
        {/* ============================================= || right column || ============================================= */}
        <Grid item xs={12} sm={4}>
          <MainCard
            title="Delivered Orders "
            content={false}
            secondary={
              <Link
                component={RouterLink}
                to="/reports/ordersdetails"
                color="primary"
              >
                View all
              </Link>
            }
          >
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell sx={{ pl: 3, textAlign: "left" }}>
                      Zones
                    </TableCell>
                    <TableCell sx={{ textAlign: "right" }}>Delivered</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {locationSummarydata.map((zone, index) => (
                    <TableRow hover key={index}>
                      <TableCell sx={{ pl: 3 }}>
                        <Grid container spacing={2} alignItems="center">
                          <Grid item>
                            <Avatar
                              sx={{
                                bgcolor:
                                  index == 0
                                    ? theme.palette.c_color.main
                                    : index == 1
                                    ? theme.palette.m_color.main
                                    : theme.palette.n_color.main,
                              }}
                            >
                              {" "}
                              {zone.locationname.charAt(0)}
                            </Avatar>
                          </Grid>
                          <Grid item xs zeroMinWidth>
                            <Typography align="left" variant="subtitle1">
                              {zone.locationname}
                            </Typography>{" "}
                          </Grid>
                        </Grid>
                      </TableCell>

                      <TableCell sx={{ textAlign: "right" }}>
                        {zone.delivered}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </MainCard>
        </Grid>
      </Grid>
      {/* ============================================= || Orders chart|| ============================================= */}
      <Grid container spacing={3} sx={{ mt: 2 }}>
        <Grid item xs={12}>
          <Grid container alignItems="center" justifyContent="space-between">
            <Grid item>
              {/* <Typography variant="h5">Orders Report</Typography> */}
            </Grid>
            <Grid item></Grid>
          </Grid>
          <SalesChart series={[series]} />
        </Grid>
      </Grid>
    </>
  );
};

export default Orders;
