import React, { useEffect, useState, useRef } from "react";
import TitleCard from "pages/titleCard";
import { useTheme } from "@mui/material/styles";
import { HiHandThumbDown, HiHandThumbUp } from "react-icons/hi2";
import LoadingIcons from "react-loading-icons";
import { Link as RouterLink } from "react-router-dom";
import { UpOutlined, DownOutlined } from "@ant-design/icons";
import VerifiedIcon from "@mui/icons-material/Verified";
import HoverSocialCard from "components/cards/statistics/HoverSocialCard";
import {
  DashboardOutlined,
  LeftOutlined,
  RightOutlined,
} from "@ant-design/icons";
import { ThemeMode } from "config";
import { CiMenuKebab } from "react-icons/ci";
import axios from "axios";
import { FaIndianRupeeSign } from "react-icons/fa6";
import { FaLocationArrow } from "react-icons/fa6";
import dayjs from "dayjs";
import { enqueueSnackbar } from "notistack";
import AddOutlinedIcon from "@mui/icons-material/AddOutlined";
import ListAltOutlinedIcon from "@mui/icons-material/ListAltOutlined";
import { FaUserCircle } from "react-icons/fa";
import { FaRegEdit } from "react-icons/fa";
import {
  Avatar,
  Link,
  Grid,
  Typography,
  Collapse,
  Paper,
  InputBase,
  IconButton,
  Divider,
  Stack,
  OutlinedInput,
  InputAdornment,
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableSortLabel,
  TableRow,
  Button,
  Menu,
  MenuItem,
  Chip,
  Dialog,
  DialogActions,
  DialogContent,
  TextField,
  FormLabel,
  DialogTitle,
  Skeleton,
  RadioGroup,
  FormControlLabel,
  FormControl,
  Radio,
  Autocomplete,
} from "@mui/material";
import PersonIcon from "@mui/icons-material/Person";

import Loader from "components/Loader";
import { PopupTransition } from "components/@extended/Transitions";

import {
  CSVExport,
  TableRowSelection,
} from "components/third-party/ReactTable";
import { visuallyHidden } from "@mui/utils";

import { SearchOutlined } from "@ant-design/icons";
import SearchIcon from "@mui/icons-material/Search";
import ClearIcon from "@mui/icons-material/Clear";
import { ExpandLess, ExpandMore, Search } from "@mui/icons-material";

import MainCard from "components/MainCard";
import { useQuery } from "@tanstack/react-query";

// table filter
function descendingComparator(a, b, orderBy) {
  if (b[orderBy] < a[orderBy]) {
    return -1;
  }
  if (b[orderBy] > a[orderBy]) {
    return 1;
  }
  return 0;
}

function getComparator(order, orderBy) {
  return order === "desc"
    ? (a, b) => descendingComparator(a, b, orderBy)
    : (a, b) => -descendingComparator(a, b, orderBy);
}

function stableSort(array, comparator) {
  const stabilizedThis = array.map((el, index) => [el, index]);
  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0]);
    if (order !== 0) return order;
    return a[1] - b[1];
  });
  return stabilizedThis.map((el) => el[0]);
}

// ==============================|| headCells||============================== //

const headCells = [
  {
    id: "tenantname",
    numeric: false,
    disablePadding: true,
    label: "Clients",
  },
];

// ==============================|| MUI TABLE - HEADER ||============================== //
function EnhancedTableHead({
  onSelectAllClick,
  order,
  orderBy,
  numSelected,
  rowCount,
  onRequestSort,
}) {
  const createSortHandler = (property) => (event) => {
    onRequestSort(event, property);
  };

  return (
    <TableHead>
      <TableRow>
        {/* <TableCell padding="checkbox" sx={{ pl: 3 }}>
          <Checkbox
            color="primary"
            indeterminate={numSelected > 0 && numSelected < rowCount}
            checked={rowCount > 0 && numSelected === rowCount}
            onChange={onSelectAllClick}
            inputProps={{
              "aria-label": "select all desserts",
            }}
          />
        </TableCell> */}
        {headCells.map((headCell) => (
          <TableCell
            key={headCell.id}
            align={headCell.numeric ? "right" : "left"}
            padding={headCell.disablePadding ? "none" : "normal"}
            sortDirection={orderBy === headCell.id ? order : undefined}
          >
            <TableSortLabel
              active={orderBy === headCell.id}
              direction={orderBy === headCell.id ? order : "asc"}
              onClick={createSortHandler(headCell.id)}
            >
              {headCell.label}
              {orderBy === headCell.id ? (
                <Box component="span" sx={visuallyHidden}>
                  {order === "desc" ? "sorted descending" : "sorted ascending"}
                </Box>
              ) : null}
            </TableSortLabel>
          </TableCell>
        ))}
      </TableRow>
    </TableHead>
  );
}

// ==============================|| Starts here||============================== //
const ClientsPricing = () => {
  const theme = useTheme();

  // const rows = allTenantsdata;
  const [allTenantsdata, setAllTenantData] = useState([]);
  const [rows, setRows] = useState([]);
  const [order, setOrder] = React.useState("asc");
  const [orderBy, setOrderBy] = React.useState("calories");
  const [selected, setSelected] = React.useState([]);
  const [page, setPage] = React.useState(0);
  const [dense] = React.useState(false);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [selectedValue, setSelectedValue] = React.useState({});
  const [anchorEl, setAnchorEl] = React.useState(null);
  const openMenu = Boolean(anchorEl);
  const [searchList, setSearchList] = useState("");
  const [filteredList, setFilteredList] = useState([]);
  const [isTenantSelected, setIsTenantSelected] = useState(false);
  const [selectedTenant, setSelectedTenant] = useState();
  const [selectedTenid, setSelectedTenid] = useState("");
  const [selectedOrderSummary, setSelectedOrderSummary] = useState({});
  const [locations, setLocations] = useState([]);
  const [dropOpen, setDropOpen] = React.useState();
  const [openIndex, setOpenIndex] = useState(null);
  const [locationsSummary, setLocationsSummary] = useState();
  const [tenantPricing, setTenanatPricing] = useState();

  const [dialogopen, setDialogopen] = useState(false);
  const [dialogopen1, setDialogopen1] = useState(false);
  const [dialogopen2, setDialogopen2] = useState(false);

  const [minkms, setMinkms] = useState("");
  const [actualkms, setActualkms] = useState("");
  const [baseprice, setBaseprice] = useState("");
  const [priceperkm, setPriceperkm] = useState("");
  const [othercharges, setOthercharges] = useState("0");
  const [pageno, setPageno] = useState(1);

  const [loading1, setLoading1] = useState(false);
  const [clientstatus, setClientstatus] = useState("");
  const [clientpricelist, setClientpricelist] = useState([]);
  const [currentindex, setCurrentindex] = useState(0);
  const [status1, setStatus1] = useState(1);
  const [managerList, setManagerList] = useState([]);
  const [manager, setManager] = useState("");
  const [isManager, setIsManager] = useState(false);
  const [managerid, setManagerid] = useState(false);
  const [id, setid] = useState();
  const [rough, setrough] = useState(true);
  const textFieldRef = useRef(null);

  const [appPricing, setAppPricing] = useState([]);
  const [selectedPricing, setSelectedPricing] = useState({});
  const [isPrice, setIsprice] = useState(true);
  const [appId, setAppId] = useState(0);
  const [locaName, setLocoName] = useState("All");
  const [locations1, setLocations1] = useState("All");

  /* ============================================= || handleKeyPress (ctrl+k)| ============================================= */
  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.key === "k" && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();

        textFieldRef.current.focus();
      }
      if (
        event.key === "Escape" &&
        document.activeElement === textFieldRef.current
      ) {
        // Remove focus from the TextField
        textFieldRef.current.blur();
      }
    };
    document.addEventListener("keydown", handleKeyPress);

    return () => {
      document.removeEventListener("keydown", handleKeyPress);
    };
  }, []);
  // ==============================|| fetchAppLocations ||============================== //
  const fetchAppLocations = async () => {
    try {
      const locationRes = await axios.get(
        `${process.env.REACT_APP_URL}/utils/getapplocations`
      );
      const updatedLocations = [
        ...locationRes.data.details,
        { locationname: "All", applocationid: 0 }, // Add your new object here
      ];
      console.log("fetchAppLocations", updatedLocations);
      setLocations1(updatedLocations);
    } catch (err) {
      console.log("locationRes", err);
    }
  };
  useEffect(() => {
    fetchAppLocations();
  }, []);
  /* ============================================= || fetchAllTenants| ============================================= */
  const fetchAllTenants = async () => {
    try {
      let url = "";
      if (searchList) {
        url = `${process.env.REACT_APP_URL}/tenants/search/?keyword=${searchList}`;
      } else {
        url =
          appId == 0
            ? `${process.env.REACT_APP_URL}/tenants/getalltenants/?status=active&pageno=${pageno}&pagesize=${rowsPerPage}`
            : `${process.env.REACT_APP_URL}/tenants/getalltenants?/status=active&applocationid=${appId}&pageno=${pageno}&pagesize=${rowsPerPage}`;
      }
      const allTenantResponse = await axios.get(url);
      console.log("fetchAllTenants", allTenantResponse.data.details);
      console.log("fetchAllTenants(0)", allTenantResponse.data.details[0]);
      setAllTenantData(allTenantResponse.data.details);
      setSelectedTenant(allTenantResponse.data.details[0]);
      setSelectedTenid(allTenantResponse.data.details[0].tenantid);
      setRows(allTenantResponse.data.details);
      setClientstatus(allTenantResponse.data.details[0].approved);
      // fetchmanagerList(allTenantResponse.data.details[0].applolcationid);
      setAppId(allTenantResponse.data.details[0].applolcationid);
      if (allTenantResponse.data.details[0].Accountname == "") {
        setIsManager(false);
      } else {
        setIsManager(true);
        setManager(allTenantResponse.data.details[0].Accountname);
      }
    } catch (error) {
      console.log("fetchAllTenants", error);
    }
  };

  useEffect(() => {
    fetchAllTenants();
  }, [pageno, searchList, appId]);

  /* ============================================= || fetchmanagerList| ============================================= */

  // const fetchmanagerList = async (id) => {
  //   try {
  //     let managerListResponse = await axios.get(
  //       `https://jupiter.nearle.app/live/api/v1/partners/getpartnerusers/?applocationid=${id}`
  //     );
  //     console.log("managerListResponse", managerListResponse.data.details);
  //     setManagerList(managerListResponse.data.details);
  //   } catch (error) {
  //     console.log("fetchmanagerList", error);
  //   }
  // };
  /* ============================================= || fetchSelectedOrderSummary || ============================================= */

  const fetchSelectedOrderSummary = async (id) => {
    try {
      let selectedOrderSummary = await axios.get(
        `https://jupiter.nearle.app/live/api/v1/orders/getordersummary/?tenantid=${id}`
      );
      console.log("selectedOrderSummary", selectedOrderSummary.data.details);
      console.log("selectedTenid", selectedTenid);
      setSelectedOrderSummary(selectedOrderSummary.data.details);
    } catch (error) {
      console.log("fetchSelectedOrderSummary", error);
    }
  };

  /* ============================================= || fetchLocations || ============================================= */

  const fetchLocations = async (tid) => {
    setLoading1(true);
    try {
      let locations = await axios.get(
        `https://jupiter.nearle.app/live/api/v1/orders/tenant/getlocationsummary/?tenantid=${tid}`
      );
      console.log("locations", locations.data.details);

      setLocations(locations.data.details || []);
      setLoading1(false);

      setDropOpen(Array(locations.length).fill(false));
    } catch (error) {
      console.log("fetchLocations", error);
      setLoading1(false);
    }
  };
  /* ============================================= || fetchclientpricelist || ============================================= */

  const fetchclientpricelist = async () => {
    await axios
      .get(
        `${process.env.REACT_APP_URL}/tenants/getpricinglist/?tenantid=${selectedTenid}`
      )
      .then((res) => {
        console.log(res);
        if (res.data.status) {
          setClientpricelist(res.data.details);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  /* ============================================= || fetchLocationsSummary || ============================================= */

  const fetchLocationsSummary = async (lid, tid) => {
    try {
      let locationsSummary = await axios.get(
        `https://jupiter.nearle.app/live/api/v1/orders/tenant/getlocationsummary/?tenantid=${tid}&locationid=${lid}`
      );
      console.log("locationsSummary", locationsSummary.data.details);

      setLocationsSummary(locationsSummary.data.details);
    } catch (error) {
      console.log("fetchLocationsSummary", error);
    }
  };
  /* ============================================= || fetchTenanatPricing || ============================================= */
  const fetchTenanatPricing = async (id) => {
    try {
      let tenantPricing = await axios.get(
        `https://jupiter.nearle.app/live/api/v1/tenants/gettenantpricing/?tenantid=${id}`
      );
      console.log("tenantPricing", tenantPricing.data.details);

      setTenanatPricing(tenantPricing.data.details);
    } catch (error) {
      console.log("fetchTenanatPricing", error);
    }
  };

  useEffect(() => {
    selectedTenid && fetchSelectedOrderSummary(selectedTenid);
    selectedTenid && fetchLocations(selectedTenid);
    selectedTenid && fetchTenanatPricing(selectedTenid);
  }, [selectedTenid]);
  /* ============================================= || getAppPricing || ============================================= */
  const getAppPricing = async (id) => {
    console.log("id", id);
    try {
      let appPricingRes = await axios.get(
        appId == 0
          ? `https://jupiter.nearle.app/live/api/v1/utils/getapppricing`
          : `https://jupiter.nearle.app/live/api/v1/utils/getapppricing/?applocationid=${id}`
      );
      console.log("appPricingRes", appPricingRes.data.details);
      setAppPricing(appPricingRes.data.details);
    } catch (error) {
      console.log("appPricingRes", error);
    }
  };
  useEffect(() => {}, [appId]);

  /* ============================================= || createpricing || ============================================= */

  const createpricing = async () => {
    await axios
      .post(`${process.env.REACT_APP_URL}/tenants/createpricing`, {
        tenantpricingid: 0,
        applocationid: appId,
        pricingid: selectedPricing.pricingid,
        tenantid: selectedTenid,
        pricingdate: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        configid: selectedPricing.configid,
        pricingtypeid: selectedPricing.pricingtypeid,
        slab: selectedPricing.slab,
        baseprice: selectedPricing.baseprice,
        priceperkm: selectedPricing.priceperkm,
        minkm: selectedPricing.minkm,
        maxkm: selectedPricing.maxkm,
        orders: selectedPricing.minorder,
        othercharges: 0,
      })
      .then((res) => {
        if (res.data.status) {
          enqueueSnackbar("Price Created Successfully", {
            variant: "success",
            anchorOrigin: { vertical: "top", horizontal: "right" },
            autoHideDuration: 2000,
          });
          dialogclose();
          fetchAllTenants();
          setSelectedPricing({});
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  /* ============================================= || tenantupdate || ============================================= */

  const tenantupdate = async () => {
    if (!tenantPricing.baseprice && clientstatus == 0) {
      opentoast("Kindly add Client Pricing");
    } else {
      setSearchList("");

      await axios
        .put(`https://jupiter.nearle.app/live/api/v1/tenants/update`, {
          tenantid: selectedTenid,
          approved: clientstatus == 0 ? 1 : 0,
        })
        .then((res) => {
          if (res.data.status) {
            enqueueSnackbar("Updated Successfully", {
              variant: "success",
              anchorOrigin: { vertical: "top", horizontal: "right" },
              autoHideDuration: 2000,
            });
            menuClose();

            setStatus1((val) => val + 1);
            fetchAllTenants();
          }
        })
        .catch((err) => {
          console.log(err);
          enqueueSnackbar(err.message, {
            variant: "error",
            anchorOrigin: { vertical: "top", horizontal: "right" },
            autoHideDuration: 2000,
          });
        });
    }
  };
  /* ============================================= || managerUpdate || ============================================= */

  const managerUpdate = async (managerid) => {
    await axios
      .put(`https://jupiter.nearle.app/live/api/v1/tenants/update`, {
        tenantid: selectedTenid,
        // approved: clientstatus == 0 ? 0 : 1,
        partneruserid: managerid,
      })
      .then((res) => {
        if (res.data.status) {
          enqueueSnackbar("User Updated Successfully", {
            variant: "success",
            anchorOrigin: { vertical: "top", horizontal: "right" },
            autoHideDuration: 1000,
          });
        }
      })
      .catch((err) => {
        console.log(err);
        enqueueSnackbar(err.message, {
          variant: "error",
          anchorOrigin: { vertical: "top", horizontal: "right" },
          autoHideDuration: 2000,
        });
      });
  };
  /* ============================================= || opentoast || ============================================= */

  const opentoast = (message) => {
    enqueueSnackbar(message, {
      variant: "error",
      anchorOrigin: { vertical: "top", horizontal: "right" },
      autoHideDuration: 2000,
    });
  };
  const toggleDropDown = (index, lid, tid) => {
    const newDropOpen = [...dropOpen];
    newDropOpen[index] = !newDropOpen[index];
    setDropOpen(newDropOpen);
    fetchLocationsSummary(lid, tid);
  };

  const handleClick = (event, row, tenantname, index) => {
    setCurrentindex(index);
    setIsTenantSelected(true);
    console.log(row);
    setSelectedTenant(row);
    setAppId(row.applolcationid);
    setManager(row.Accountname);
    if (row.Accountname == "") {
      setIsManager(false);
    } else {
      setIsManager(true);
    }
    setSelectedTenid(row.tenantid);
    setClientstatus(row.approved);
    const selectedIndex = selected.indexOf(tenantname);
    let newSelected = {};
    // if (selectedIndex === -1) {
    //   newSelected = newSelected.concat(selected, tenantname);
    // } else if (selectedIndex === 0) {
    //   newSelected = newSelected.concat(selected.slice(1));
    // } else if (selectedIndex === selected.length - 1) {
    //   newSelected = newSelected.concat(selected.slice(0, -1));
    // } else if (selectedIndex > 0) {
    //   newSelected = newSelected.concat(
    //     selected.slice(0, selectedIndex),
    //     selected.slice(selectedIndex + 1)
    //   );
    // }
    // const selectedRowData = rows.filter((row) =>
    //   newSelected.includes(row.tenantname.toString())
    // );
    // setSelectedValue(selectedRowData);
    // setSelected(newSelected);
    // setSelected(row);
  };

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event?.target.value, 10));
    setPage(0);
  };

  const isSelected = (tenantname) => selected.indexOf(tenantname) !== -1;

  // Avoid a layout jump when reaching the last page with empty rows.
  const emptyRows =
    page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0;

  // if (isLoadingAllTenants) return <Loader />;

  // if (isErrorAllTenants)
  //   return (
  //     "An error has occurred:(isErrorAllTenants) " + allTenantsError.message
  //   );
  const handleSearch = (event) => {
    const searchQuery = event.target.value;
    setSearchList(searchQuery);

    const filtered = allTenantsdata.filter(
      (item) =>
        item.tenantname.toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.primarycontact.includes(searchQuery)
    );
    // setFilteredList(filtered);
    setRows(filtered);
  };
  const menuOpen = (event) => {
    setAnchorEl(event.currentTarget);
  };
  const menuClose = () => {
    setAnchorEl(null);
  };

  const dialogclose = () => {
    setDialogopen(false);
    setMinkms("");
    setBaseprice("");
    setPriceperkm("");
    setOthercharges("");
  };

  const dialogclose1 = () => {
    setDialogopen1(false);
  };
  const dialogclose2 = () => {
    setDialogopen2(false);
  };

  return (
    <>
      <Stack
        direction={"row"}
        justifyContent="space-between"
        alignItems="center"
        sx={{ my: 1 }}
      >
        <TitleCard title="Pricing" />
        <Autocomplete
          disablePortal
          id="combo-box-demo"
          options={locations1 || []}
          getOptionLabel={(option) => `${option.locationname}`}
          sx={{ width: 430, height: "30px", ml: 3, zIndex: "100", mt: -3 }}
          onChange={(event, value, reason) => {
            if (reason === "clear") {
              setAppId(0);
              setLocoName("Select  Locations");
            } else {
              console.log(value);
              setAppId(value.applocationid);
              setLocoName(value.locationname);
            }
          }}
          renderInput={(params) => <TextField {...params} label={locaName} />}
        />{" "}
      </Stack>
      <Grid container spacing={0} sx={{ height: "100%" }}>
        {/* // ==============================|| tenant list  ||============================== // */}
        <Grid item xs={3.5} sx={{ height: "100%" }}>
          <MainCard
            elevation={0}
            title={
              <>
                <Stack spacing={2} sx={{ py: 0.2 }}>
                  <OutlinedInput
                    inputRef={textFieldRef}
                    fullWidth
                    id="input-search-header"
                    placeholder="Search (ctrl+k)"
                    value={searchList}
                    onChange={(e) => setSearchList(e.target.value)}
                    // onChange={handleSearch}
                    sx={{
                      "& .MuiOutlinedInput-input": {
                        p: "10.5px 0px 12px",
                      },
                      bgcolor: "white",
                    }}
                    startAdornment={
                      <InputAdornment position="start">
                        <SearchOutlined style={{ fontSize: "small" }} />
                      </InputAdornment>
                    }
                    endAdornment={
                      <IconButton
                        sx={{ visibility: searchList ? "visible" : "hidden" }}
                        onClick={() => {
                          setSearchList("");
                          setRows([...allTenantsdata]);
                        }}
                      >
                        <ClearIcon />
                      </IconButton>
                    }
                    autoComplete="off"
                  />
                </Stack>
              </>
            }
            content={false}
          >
            <TableRowSelection
            // selected={selected.length}
            />

            {/* table */}
            <TableContainer
              sx={{
                height: "667px",
                overflow: "scroll",
                "&::-webkit-scrollbar": {
                  width: "3px", // Customize the width of the scrollbar
                },
                "&::-webkit-scrollbar-thumb": {
                  backgroundColor: "#65387A", // Customize the scrollbar thumb color
                },
              }}
            >
              <Table
                sx={{ width: "100%" }}
                aria-labelledby="tableTitle"
                size={dense ? "small" : "medium"}
              >
                {/* <EnhancedTableHead
                  numSelected={selected.length}
                  order={order}
                  orderBy={orderBy}
                  onSelectAllClick={handleSelectAllClick}
                  onRequestSort={handleRequestSort}
                  rowCount={rows.length}
                /> */}
                <TableBody>
                  {stableSort(rows, getComparator(order, orderBy))
                    .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                    .map((row, index) => {
                      if (typeof row === "number") return null;
                      const isItemSelected = isSelected(row.tenantname);
                      const labelId = `enhanced-table-checkbox-${index}`;

                      return (
                        <TableRow
                          hover
                          onClick={(event) =>
                            handleClick(event, row, row.tenantname, index)
                          }
                          role="checkbox"
                          aria-checked={isItemSelected}
                          tabIndex={-1}
                          key={row.tenantname}
                          selected={isItemSelected}
                          sx={{ cursor: "pointer" }}
                        >
                          {/* <TableCell sx={{ pl: 3 }} padding="checkbox">
                            <Checkbox
                              color="primary"
                              checked={isItemSelected}
                              inputProps={{
                                "aria-labelledby": labelId,
                              }}
                            />
                          </TableCell> */}
                          <TableCell
                            component="th"
                            id={labelId}
                            scope="row"
                            padding="none"
                          >
                            <Grid container spacing={1} alignItems="center">
                              <Grid item>
                                <Avatar
                                  alt={row.tenantname}
                                  sx={{ bgcolor: theme.palette.primary.main }}
                                >
                                  {row.tenantname.charAt(0)}
                                </Avatar>
                              </Grid>
                              <Grid item xs zeroMinWidth>
                                <Stack direction={"row"} spacing={1}>
                                  <Typography align="left" variant="subtitle1">
                                    {row.tenantname}
                                  </Typography>
                                  {row.approved == 1 && (
                                    <VerifiedIcon
                                      fontSize="small"
                                      color="success"
                                    />
                                  )}
                                </Stack>
                                <Stack
                                  direction={"row"}
                                  sx={{
                                    display: "flex",
                                    justifyContent: "space-between",
                                  }}
                                >
                                  <Typography
                                    align="left"
                                    variant="caption"
                                    color="secondary"
                                  >
                                    {`${row.primarycontact} `}
                                  </Typography>
                                </Stack>
                              </Grid>
                            </Grid>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  {emptyRows > 0 && (
                    <TableRow sx={{ height: (dense ? 33 : 53) * emptyRows }}>
                      <TableCell colSpan={6} />
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </TableContainer>
            <Divider />
            {/* table pagination */}
            {/* <TablePagination
              sx={{ bgcolor: "#fafafa", display: "flex" ,width:'100%'}}
              rowsPerPageOptions={[5, 10, 25]}
              component="div"
              count={rows.length}
              rowsPerPage={rowsPerPage}
              page={page}
              onPageChange={handleChangePage}
              onRowsPerPageChange={handleChangeRowsPerPage}
            /> */}

            <Box
              // sx={{ p: 3, pt: 1, pl: 5 }}
              sx={{ width: "100%", px: 2, py: 1.2, bgcolor: "#eee" }}
            >
              <Grid container>
                <Grid item xs={12}>
                  <Stack
                    direction={"row"}
                    justifyContent={"flex-end"}
                    alignItems={"center"}
                    spacing={1}
                  >
                    <IconButton
                      color="primary"
                      size="small"
                      onClick={() => {
                        let val = pageno;
                        if (val > 1) {
                          val = val - 1;
                          setPageno(val);
                        }
                      }}
                    >
                      <LeftOutlined />
                    </IconButton>
                    <Typography variant="h6">{pageno}</Typography>
                    <IconButton
                      color="primary"
                      size="small"
                      onClick={() => {
                        let val = pageno;
                        if (
                          val > 0
                          // &&(!search)
                        ) {
                          if (allTenantsdata.length < rowsPerPage) {
                            setPageno(val);
                          } else {
                            val = val + 1;
                            setPageno(val);
                          }
                        }
                      }}
                    >
                      <RightOutlined />
                    </IconButton>
                  </Stack>
                </Grid>
              </Grid>
            </Box>
          </MainCard>
        </Grid>

        {/* // ==============================|| tenant details ||============================== // */}
        <Grid
          item
          xs={8.5}
          sx={{ height: "100%", border: "1px solid #eeeeee" }}
        >
          <MainCard
            sx={{ height: "100%" }}
            elevation={0}
            title={
              <>
                {selectedTenant && (
                  <Grid container spacing={2} alignItems="center">
                    <Grid item>
                      <Avatar
                        alt={selectedTenant.tenantname}
                        sx={{ bgcolor: theme.palette.primary.main }}
                      >
                        {`${selectedTenant.tenantname}`.charAt(0)}
                      </Avatar>
                    </Grid>
                    <Grid item xs zeroMinWidth>
                      <Typography align="left" variant="subtitle1">
                        {selectedTenant.tenantname}
                      </Typography>
                      <Stack
                        direction={"row"}
                        spacing={1}
                        sx={{
                          display: "flex",
                          // justifyContent: "space-between",
                        }}
                      >
                        <Typography
                          align="left"
                          variant="caption"
                          color="secondary"
                          sx={{ mr: 2 }}
                        >
                          {`${selectedTenant.primarycontact} `}
                        </Typography>
                        {clientstatus == 0 ? (
                          <Chip label="Disabled" size="small" />
                        ) : (
                          <Chip label="Active" color="success" size="small" />
                        )}
                      </Stack>
                    </Grid>
                  </Grid>
                )}
              </>
            }
            content={false}
            secondary={
              <stack>
                <IconButton
                  id="basic-button"
                  aria-controls={openMenu ? "basic-menu" : undefined}
                  aria-haspopup="true"
                  aria-expanded={openMenu ? "true" : undefined}
                  onClick={menuOpen}
                  color="primary"
                  sx={{
                    bgcolor: "#fafafa",
                    border: "1px solid #662582",
                    ml: 2,
                  }}
                >
                  {<CiMenuKebab />}
                </IconButton>
                <Menu
                  id="basic-menu"
                  anchorEl={anchorEl}
                  open={openMenu}
                  onClose={menuClose}
                  MenuListProps={{
                    "aria-labelledby": "basic-button",
                  }}
                >
                  {" "}
                  <MenuItem
                    onClick={() => {
                      tenantupdate();
                      // window.location.reload();
                    }}
                  >
                    {clientstatus == 0 ? "Approve" : "Disable"}
                  </MenuItem>
                </Menu>
              </stack>
            }
          >
            <Grid container spacing={2} sx={{ px: 0, mb: 0, height: "100%" }}>
              {/* // ==============================|| row 1 ||============================== // */}

              <Grid item xs={12}>
                {isTenantSelected ? (
                  <Grid container spacing={1} sx={{ mt: 1, mb: -1, px: 1 }}>
                    <Grid item xs={12} lg={3} sm={6}>
                      <HoverSocialCard
                        primary="Orders"
                        secondary={selectedOrderSummary.total}
                        iconPrimary={DashboardOutlined}
                        color={theme.palette.primary.main}
                      />
                    </Grid>{" "}
                    <Grid item xs={12} lg={3} sm={6}>
                      <HoverSocialCard
                        primary="Delivered"
                        secondary={selectedOrderSummary.delivered}
                        iconPrimary={HiHandThumbUp}
                        color={theme.palette.success.main}
                      />
                    </Grid>
                    <Grid item xs={12} lg={3} sm={6}>
                      <HoverSocialCard
                        primary="Pending"
                        secondary={selectedOrderSummary.pending}
                        iconPrimary={LoadingIcons.ThreeDots}
                        color={
                          theme.palette.mode === ThemeMode.DARK
                            ? theme.palette.secondary.lighter
                            : theme.palette.warning.main
                        }
                      />
                    </Grid>
                    <Grid item xs={12} lg={3} sm={6}>
                      <HoverSocialCard
                        primary="Cancelled"
                        secondary={selectedOrderSummary.cancelled}
                        iconPrimary={HiHandThumbDown}
                        color={theme.palette.secondary.main}
                      />
                    </Grid>
                  </Grid>
                ) : (
                  <Grid container spacing={1} sx={{ mt: -0.5, mb: -1, px: 1 }}>
                    <Grid item xs={12} lg={3} sm={6}>
                      <HoverSocialCard
                        primary="Orders"
                        secondary={selectedOrderSummary.total}
                        iconPrimary={DashboardOutlined}
                        color={theme.palette.primary.main}
                      />
                    </Grid>{" "}
                    <Grid item xs={12} lg={3} sm={6}>
                      <HoverSocialCard
                        primary="Delivered"
                        secondary={selectedOrderSummary.delivered}
                        iconPrimary={HiHandThumbUp}
                        color={theme.palette.success.main}
                      />
                    </Grid>
                    <Grid item xs={12} lg={3} sm={6}>
                      <HoverSocialCard
                        primary="Pending"
                        secondary={selectedOrderSummary.pending}
                        iconPrimary={LoadingIcons.ThreeDots}
                        color={
                          theme.palette.mode === ThemeMode.DARK
                            ? theme.palette.secondary.lighter
                            : theme.palette.warning.main
                        }
                      />
                    </Grid>
                    <Grid item xs={12} lg={3} sm={6}>
                      <HoverSocialCard
                        primary="Cancelled"
                        secondary={selectedOrderSummary.cancelled}
                        iconPrimary={HiHandThumbDown}
                        color={theme.palette.secondary.main}
                      />
                    </Grid>
                  </Grid>
                )}
              </Grid>
              {/* // ==============================|| row 2  ||============================== // */}

              <Grid item xs={12} sx={{ mt: 1 }}>
                <Grid container xs={12} sx={{ px: 1 }}>
                  <Grid item xs={12}>
                    <MainCard
                      elevation={0}
                      title={
                        <>
                          <Stack
                            direction={"row"}
                            justifyContent={"space-between"}
                            alignItems={"center"}
                          >
                            <Typography variant="h4">Client Pricing</Typography>
                            <Stack direction={"row"} spacing={2}>
                              <IconButton
                                variant="outlined"
                                color="primary"
                                sx={{ border: "1px solid #662582" }}
                                onClick={() => {
                                  setDialogopen(true);
                                  getAppPricing(appId);
                                }}
                              >
                                <AddOutlinedIcon />
                              </IconButton>

                              <IconButton
                                variant="outlined"
                                color="primary"
                                sx={{ border: "1px solid #662582" }}
                                onClick={() => {
                                  fetchclientpricelist();
                                  setDialogopen1(true);
                                }}
                              >
                                <ListAltOutlinedIcon />
                              </IconButton>
                            </Stack>
                          </Stack>
                        </>
                      }
                      content={false}
                      secondary={null}
                    >
                      {" "}
                      {tenantPricing && (
                        <Grid
                          container
                          spacing={1}
                          // sx={{ mt: -2, mb: 0 }}
                        >
                          <Grid item xs={12} lg={3} sm={6}>
                            <HoverSocialCard
                              primary={`Base Price (₹)`}
                              secondary={`₹ ${tenantPricing.baseprice}`}
                              iconPrimary={FaIndianRupeeSign}
                              color={theme.palette.info.main}
                            />
                          </Grid>{" "}
                          <Grid item xs={12} lg={3} sm={6}>
                            <HoverSocialCard
                              primary="Price/(km)"
                              secondary={`₹ ${tenantPricing.priceperkm}`}
                              iconPrimary={FaIndianRupeeSign}
                              color={theme.palette.info.main}
                            />
                          </Grid>
                          <Grid item xs={12} lg={3} sm={6}>
                            <HoverSocialCard
                              primary="Min (km)"
                              secondary={`${tenantPricing.minkm}`}
                              iconPrimary={FaLocationArrow}
                              color={
                                theme.palette.mode === ThemeMode.DARK
                                  ? theme.palette.secondary.lighter
                                  : theme.palette.info.main
                              }
                            />
                          </Grid>
                          <Grid item xs={12} lg={3} sm={6}>
                            <HoverSocialCard
                              primary="Other Charges (₹)"
                              secondary={`₹ ${tenantPricing.othercharges}`}
                              iconPrimary={FaIndianRupeeSign}
                              color={theme.palette.info.main}
                            />
                          </Grid>
                        </Grid>
                      )}
                    </MainCard>
                  </Grid>
                </Grid>{" "}
              </Grid>
              {/* // ==============================|| row 3 ||============================== // */}

              <Grid
                item
                xs={12}
                // sx={{ mt: -4 }}
              >
                <Grid container xs={12}>
                  <Grid item xs={12}>
                    <MainCard
                      elevation={0}
                      title={"Location"}
                      content={false}
                      secondary={null}
                    >
                      <TableContainer
                        sx={{
                          height: "352px",
                          overflowY: "scroll",
                          "&::-webkit-scrollbar": {
                            width: "3px", // Customize the width of the scrollbar
                          },
                          "&::-webkit-scrollbar-thumb": {
                            backgroundColor: "#65387A", // Customize the scrollbar thumb color
                          },
                        }}
                      >
                        <Table>
                          <TableHead>
                            <TableRow>
                              <TableCell>#</TableCell>
                              <TableCell sx={{ textAlign: "left" }}>
                                Location
                              </TableCell>
                              <TableCell sx={{ textAlign: "left" }}>
                                Total
                              </TableCell>
                              <TableCell sx={{ textAlign: "left" }}>
                                Created
                              </TableCell>
                              <TableCell sx={{ textAlign: "left" }}>
                                Pending
                              </TableCell>
                              <TableCell sx={{ textAlign: "left" }}>
                                Delivered
                              </TableCell>
                              <TableCell sx={{ textAlign: "left" }}>
                                Cancelled
                              </TableCell>
                            </TableRow>
                          </TableHead>
                          {loading1 ? (
                            <>
                              <TableBody>
                                {[1, 2, 3, 4, 5].map((loco, index) => (
                                  <React.Fragment key={index}>
                                    <TableRow hover key={index}>
                                      <TableCell sx={{}}>
                                        {/* {index + 1} */}
                                        <Skeleton
                                          variant="text"
                                          animation="wave"
                                        />
                                      </TableCell>
                                      <TableCell sx={{}}>
                                        {/* {loco.locationname} */}
                                        <Skeleton
                                          variant="text"
                                          animation="wave"
                                        />
                                      </TableCell>
                                      <TableCell sx={{ textAlign: "left" }}>
                                        {/* {loco.total} */}
                                        <Skeleton
                                          variant="text"
                                          animation="wave"
                                        />
                                      </TableCell>
                                      <TableCell sx={{ textAlign: "left" }}>
                                        {/* {loco.created} */}
                                        <Skeleton
                                          variant="text"
                                          animation="wave"
                                        />
                                      </TableCell>
                                      <TableCell sx={{ textAlign: "left" }}>
                                        {/* {loco.pending} */}
                                        <Skeleton
                                          variant="text"
                                          animation="wave"
                                        />
                                      </TableCell>
                                      <TableCell sx={{ textAlign: "left" }}>
                                        {/* {loco.delivered} */}
                                        <Skeleton
                                          variant="text"
                                          animation="wave"
                                        />
                                      </TableCell>
                                      <TableCell sx={{ textAlign: "left" }}>
                                        {/* {loco.cancelled} */}
                                        <Skeleton
                                          variant="text"
                                          animation="wave"
                                        />
                                      </TableCell>
                                    </TableRow>
                                  </React.Fragment>
                                ))}
                              </TableBody>
                            </>
                          ) : (
                            <>
                              <TableBody>
                                {locations.map((loco, index) => (
                                  <React.Fragment key={index}>
                                    <TableRow hover key={index}>
                                      <TableCell sx={{}}>{index + 1}</TableCell>
                                      <TableCell sx={{}}>
                                        {loco.locationname}
                                      </TableCell>
                                      <TableCell sx={{ textAlign: "left" }}>
                                        {loco.total}
                                      </TableCell>
                                      <TableCell sx={{ textAlign: "left" }}>
                                        {loco.created}
                                      </TableCell>
                                      <TableCell sx={{ textAlign: "left" }}>
                                        {loco.pending}
                                      </TableCell>
                                      <TableCell sx={{ textAlign: "left" }}>
                                        {loco.delivered}
                                      </TableCell>
                                      <TableCell sx={{ textAlign: "left" }}>
                                        {loco.cancelled}
                                      </TableCell>
                                    </TableRow>
                                  </React.Fragment>
                                ))}
                              </TableBody>
                            </>
                          )}
                        </Table>
                      </TableContainer>
                    </MainCard>
                  </Grid>
                </Grid>
              </Grid>
            </Grid>
          </MainCard>
        </Grid>
      </Grid>
      {/* // ==============================||( Client Pricing ) dialog (dialogopen) ||============================== // */}
      <Dialog
        fullWidth={true}
        open={dialogopen}
        onClose={dialogclose}
        scroll={"paper"}
        maxWidth="sm"
        TransitionComponent={PopupTransition}
      >
        <DialogTitle
          sx={{
            bgcolor: "#662582",
            color: "#fff",
            fontSize: "20px",
          }}
        >
          Client Pricing
        </DialogTitle>

        <DialogContent dividers={true}>
          <MainCard sx={{ height: "100%" }}>
            <Grid container spacing={2.5} alignItems={"center"}>
              <Grid item xs={12} sm={6}>
                <FormLabel>Select Slab</FormLabel>
                <Autocomplete
                  disablePortal
                  id="combo-box-demo"
                  options={appPricing}
                  getOptionLabel={(option) => `${option.slab}`}
                  fullWidth
                  selectOnFocus
                  renderInput={(params) => (
                    <TextField {...params} label="Slab" />
                  )}
                  onChange={(event, value, reason) => {
                    setSelectedPricing(value);
                    console.log("pricing", value);
                    setIsprice(false);

                    if (reason === "clear") {
                      setIsprice(true);
                    }
                  }}
                />
              </Grid>

              <Grid item xs={12} sm={6}>
                <FormLabel>Base Price</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={(selectedPricing && selectedPricing.baseprice) || 0}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Price/Km</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={(selectedPricing && selectedPricing.priceperkm) || 0}
                />
              </Grid>

              <Grid item xs={12} sm={6}>
                <FormLabel>Min Kms</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={(selectedPricing && selectedPricing.minkm) || 0}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Max Kms</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={(selectedPricing && selectedPricing.maxkm) || 0}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Min Orders</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={(selectedPricing && selectedPricing.minorder) || 0}
                />
              </Grid>
            </Grid>
          </MainCard>
        </DialogContent>
        <DialogActions>
          <Grid container>
            <Grid item xs={12}>
              <Stack
                direction={"row"}
                justifyContent={"flex-end"}
                spacing={2}
                sx={{ p: 2 }}
              >
                <Button
                  disabled={isPrice}
                  variant="contained"
                  onClick={() => {
                    createpricing();
                  }}
                >
                  Save
                </Button>
                <Button
                  variant="contained"
                  onClick={() => {
                    dialogclose();
                    setSelectedPricing({});
                  }}
                  color="error"
                >
                  Cancel
                </Button>
              </Stack>
            </Grid>
          </Grid>
        </DialogActions>
      </Dialog>
      {/* // ==============================||(Client Pricing List )dialog (dialogopen1) ||============================== // */}
      <Dialog
        fullWidth={true}
        open={dialogopen1}
        onClose={dialogclose1}
        scroll={"paper"}
        maxWidth="sm"
        TransitionComponent={PopupTransition}
      >
        <DialogTitle
          sx={{
            bgcolor: "#662582",
            color: "#fff",
          }}
        >
          Client Pricing List
        </DialogTitle>

        <DialogContent dividers={true}>
          {/* <MainCard
            sx={{ height: '100%' }}
          > */}
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>#</TableCell>
                  <TableCell>Date</TableCell>
                  <TableCell>Base Price</TableCell>
                  <TableCell>Min Kms</TableCell>
                  <TableCell>Price/Km</TableCell>
                  <TableCell>Other Charges</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {clientpricelist.map((val, i) => {
                  return (
                    <>
                      <TableRow>
                        <TableCell>{i + 1}</TableCell>
                        <TableCell>
                          {dayjs(val.pricingdate).format("DD-MM-YYYY")}
                        </TableCell>
                        <TableCell>{val.baseprice}</TableCell>
                        <TableCell>{val.minkm}</TableCell>
                        <TableCell>{val.priceperkm}</TableCell>
                        <TableCell>{val.othercharges}</TableCell>
                      </TableRow>
                    </>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
          {/* </MainCard > */}
        </DialogContent>
        <DialogActions>
          <Grid container>
            <Grid item xs={12}>
              <Stack
                direction={"row"}
                justifyContent={"flex-end"}
                spacing={2}
                sx={{ p: 2 }}
              >
                {/* <Button variant='contained'
                  onClick={() => {

                  }}
                >Add
                </Button> */}
                <Button
                  variant="contained"
                  onClick={() => {
                    dialogclose1();
                  }}
                  color="error"
                >
                  Close
                </Button>
              </Stack>
            </Grid>
          </Grid>
        </DialogActions>
      </Dialog>
      {/* // ==============================|| ac manager dialog (dialogopen2)||============================== // */}
      <Dialog
        fullWidth={true}
        open={dialogopen2}
        onClose={dialogclose2}
        scroll={"paper"}
        maxWidth="sm"
        TransitionComponent={PopupTransition}
      >
        <DialogTitle
          sx={{
            bgcolor: "#662582",
            color: "#fff",
          }}
        >
          Account Manager
        </DialogTitle>
        <Stack
          fullWidth
          sx={{
            bgcolor: "#eeeeee",
            display: "flex",
            flexDirection: "row",
            justifyContent: "space-between",
            width: "100%",
            px: 3,
            py: 2,
          }}
        >
          <Typography variant="h5">USER</Typography>
          <Typography variant="h5">SELECT</Typography>
        </Stack>
        <DialogContent dividers={true}>
          <FormControl fullWidth sx={{}}>
            {/* <FormLabel id="demo-radio-buttons-group-label">Gender</FormLabel> */}
            <RadioGroup
              aria-labelledby="demo-radio-buttons-group-label"
              name="radio-buttons-group"
            >
              {managerList.map((list, index) => (
                <Grid
                  key={index}
                  container
                  justifyContent="space-between"
                  onClick={() => {
                    setIsManager(true);
                    setManager(list.fullname);
                    setManagerid(list.userid);
                  }}
                  sx={{}}
                >
                  <Grid item>
                    <Typography variant="caption" sx={{ fontSize: "18px" }}>
                      {list.fullname}
                    </Typography>
                    <br />
                    <Typography
                      variant="caption"
                      color={"secondary"}
                      sx={{ fontSize: "12px" }}
                    >
                      {list.contactno}
                    </Typography>
                  </Grid>
                  <Grid item>
                    <FormControlLabel
                      value="Joshi"
                      control={<Radio />}
                      // label="Female"
                    />
                  </Grid>
                </Grid>
              ))}
            </RadioGroup>
          </FormControl>
        </DialogContent>
        <DialogActions>
          <Grid container>
            <Grid item xs={12}>
              <Stack
                direction={"row"}
                justifyContent={"flex-end"}
                spacing={2}
                sx={{ p: 2 }}
              >
                <Button
                  variant="contained"
                  onClick={() => {
                    dialogclose2();
                    managerUpdate(managerid);
                    setrough(!rough);
                  }}
                  color="success"
                >
                  OK
                </Button>
              </Stack>
            </Grid>
          </Grid>
        </DialogActions>
      </Dialog>
    </>
  );
};

export default ClientsPricing;
