import React, { useEffect, useState, useRef, useMemo } from "react";
import TitleCard from "pages/titleCard";
import MainCard from "components/MainCard";
import axios from "axios";
import { useTheme } from "@mui/material/styles";
import Loader from "components/Loader";
import { Empty } from "antd";
import dayjs from "dayjs";
import { enqueueSnackbar } from "notistack";
import Geocode from "react-geocode";
import LocationOnIcon from "@mui/icons-material/LocationOn";
import parse from "autosuggest-highlight/parse";
import { debounce } from "@mui/material/utils";
import {
  OutlinedInput,
  Stack,
  Table,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TableBody,
  Typography,
  InputAdornment,
  IconButton,
  Box,
  Grid,
  useMediaQuery,
  Autocomplete,
  TextField,
  Tooltip,
  Collapse,
  Tab,
  Tabs,
  Divider,
  Card,
  CardHeader,
  Avatar,
  CardContent,
  CardActions,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormLabel,
  Chip,
} from "@mui/material";
import {
  SearchOutlined,
  CloseOutlined,
  LeftOutlined,
  RightOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
  EditOutlined,
  IssuesCloseOutlined,
  StopOutlined,
} from "@ant-design/icons";
import { PopupTransition } from "components/@extended/Transitions";
import { FaRegCheckCircle } from "react-icons/fa";
import { TbBrandDatabricks } from "react-icons/tb";
import { GiMoneyStack } from "react-icons/gi";
import { FiUser } from "react-icons/fi";
import { FaRegAddressCard } from "react-icons/fa";
import { TbCategoryMinus } from "react-icons/tb";
import { MdMyLocation } from "react-icons/md";
import { GiModernCity } from "react-icons/gi";
import { MdNumbers } from "react-icons/md";
import { TbWorldLongitude } from "react-icons/tb";
import { TbWorldLatitude } from "react-icons/tb";
import { FaRegCircleUser } from "react-icons/fa6";
import { TbListDetails } from "react-icons/tb";
import { FiPhoneCall } from "react-icons/fi";
import { LuMail } from "react-icons/lu";
import { BiUser } from "react-icons/bi";
import { BiRegistered } from "react-icons/bi";
import { PiUsersThree } from "react-icons/pi";

// ==============================|| Starts here||============================== //
const Clients = () => {
  const textFieldRef = useRef(null);
  const [search, setSearch] = useState("");
  const [pageno, setPageno] = useState(1);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [allClientsdata, setAllClientData] = useState([]);
  const theme = useTheme();
  const [isloader, setisloader] = useState(false);
  const matchDownSM = useMediaQuery(theme.breakpoints.up("sm"));
  const [appId, setAppId] = useState(0);
  const [locaName, setLocoName] = useState("All");
  const [locations, setLocations] = useState("All");
  const [openRow, setOpenRow] = useState(null); // Initially no row is open
  const [openRow1, setOpenRow1] = useState(null); // Initially no row is open
  const [value, setValue] = React.useState(null);
  const [value0, setValue0] = useState(0);
  const [value1, setValue1] = useState(0);
  const [value2, setValue2] = useState(0);
  const [selectedTenid, setSelectedtenid] = useState();
  const [clientpricelist, setClientpricelist] = useState([]);
  const [clientstatus, setClientstatus] = useState("");
  const [tenantPricing, setTenanatPricing] = useState();
  const [status, setstatus] = useState("active");
  const [selectedCustomer, setSelectedCustomer] = useState({}); // to edit
  const [dialogopen, setDialogopen] = useState(false);
  const [appPricing, setAppPricing] = useState([]);
  const [selectedPricing, setSelectedPricing] = useState({});
  const [isPrice, setIsprice] = useState(true);
  const [address, setAddress] = useState("");
  const [city, setCity] = useState("");
  const [zipcode, setZipcode] = useState("");
  const [state, setState] = useState("");
  const [suburb, setSuburb] = useState("");
  const [lati, setLati] = useState("");
  const [longi, setLongi] = useState("");
  const [latlong, setLatlong] = useState({});
  const [editClient, setEditClient] = useState({});
  const dialogclose = () => {
    setDialogopen(false);
  };

  const handleChange = (event, newValue) => {
    console.log("newValue(status)", newValue);
    setValue0(newValue);
    setSearch("");
  };
  const handleChange1 = (event, newValue1) => {
    console.log("newValue1", newValue1);
    setValue1(newValue1);
  };
  const handleChange2 = (event, newValue2) => {
    console.log("newValue2", newValue2);
    setValue2(newValue2);
  };

  const [openRowIndex1, setOpenRowIndex1] = useState(null); // Initially no row is open for collapsible section 1
  const [openRowIndex2, setOpenRowIndex2] = useState(null); // Initially no row is open for collapsible section 2
  // Handle toggling for collapsible section 1
  const handleCollapseToggle1 = (rowIndex) => {
    setOpenRowIndex1((prevIndex) => (prevIndex === rowIndex ? null : rowIndex));
  };
  // Handle toggling for collapsible section 2
  const handleCollapseToggle2 = (rowIndex) => {
    setOpenRowIndex2((prevIndex) => (prevIndex === rowIndex ? null : rowIndex));
  };
  useEffect(() => {
    console.log("selectedCustomer", selectedCustomer);
  }, [selectedCustomer]);
  useEffect(() => {
    setOpenRowIndex1(-1);
    setOpenRowIndex2(-1);
  }, [value0]);
  // ==============================|| formatNumberToRupees ||============================== //
  function formatNumberToRupees(value) {
    return new Intl.NumberFormat("en-IN", {
      style: "currency",
      currency: "INR",
      minimumFractionDigits: 2,
    }).format(value);
  }
  /* ============================================= || opentoast || ============================================= */

  const opentoast = (message, variant, duration) => {
    enqueueSnackbar(message, {
      variant: variant,
      anchorOrigin: { vertical: "top", horizontal: "right" },
      autoHideDuration: duration,
    });
  };
  // ==============================|| google address ||============================== //
  const GOOGLE_MAPS_API_KEY = process.env.REACT_APP_GOOGLE_MAPS_API_KEY;

  function loadScript(src, position, id) {
    if (!position) {
      return;
    }

    const script = document.createElement("script");
    script.setAttribute("async", "");
    script.setAttribute("id", id);
    script.src = src;
    position.appendChild(script);
  }

  const autocompleteService = { current: null };
  // ==============================|| for google address ||============================== //
  const [value3, setValue3] = useState(null);
  const [inputValue, setInputValue] = useState("");
  const [options, setOptions] = useState([]);
  const loaded = useRef(false);
  if (typeof window !== "undefined" && !loaded.current) {
    if (!document.querySelector("#google-maps")) {
      loadScript(
        `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAPS_API_KEY}&libraries=places`,
        document.querySelector("head"),
        "google-maps"
      );
    }

    loaded.current = true;
  }

  const fetch = useMemo(
    () =>
      debounce((request, callback) => {
        autocompleteService.current.getPlacePredictions(request, callback);
      }, 400),
    []
  );
  useEffect(() => {
    let active = true;

    if (!autocompleteService.current && window.google) {
      autocompleteService.current =
        new window.google.maps.places.AutocompleteService();
    }
    if (!autocompleteService.current) {
      return undefined;
    }

    if (inputValue === "") {
      setOptions(value ? [value] : []);
      return undefined;
    }
    fetch({ input: inputValue }, (results) => {
      if (active) {
        let newOptions = [];

        if (value) {
          newOptions = [value];
        }

        if (results) {
          newOptions = [...newOptions, ...results];
        }
        setOptions(newOptions);
      }
    });

    return () => {
      active = false;
    };
  }, [value, inputValue, fetch]);

  Geocode.setApiKey(process.env.REACT_APP_GOOGLE_MAPS_API_KEY);
  useEffect(() => {
    try {
      console.log("selected address =>", address);
      Geocode.fromAddress(address).then(
        (response) => {
          console.log("lat long response =>", response.results[0]);
          if (response.status == "OK") {
            const { lat, lng } = response.results[0].geometry.location;
            setLatlong({
              lat,
              lng,
            });
            setEditClient({
              ...editClient,
              latitude: lat.toString(),
              longitude: lng.toString(),
            });

            if (response.results[0].address_components) {
              let place = response.results[0];
              let city1, zipcode1, state1, suburb1;
              for (let i = 0; i < place.address_components.length; i++) {
                for (
                  let j = 0;
                  j < place.address_components[i].types.length;
                  j++
                ) {
                  switch (place.address_components[i].types[j]) {
                    case "locality":
                      city1 = place.address_components[i].long_name;
                      break;
                    case "administrative_area_level_1":
                      state1 = place.address_components[i].long_name;
                      break;
                    case "postal_code":
                      zipcode1 = place.address_components[i].long_name;
                      break;
                    case "sublocality":
                      suburb1 = place.address_components[i].long_name;
                      break;
                  }
                }
              }
              setCity(city1 || "");
              setState(state1 || "");
              setZipcode(zipcode1 || "");
              setSuburb(suburb1 || "");
              setEditClient({
                ...editClient,
                city: city1 || "",
                state: state1 || "",
                postcode: zipcode || "",
                suburb: suburb1 || "",
              });
            }
          }
        },
        (error) => {
          console.log(error);
        }
      );
    } catch (err) {
      console.log(err);
    }
  }, [address]);

  useEffect(() => {
    selectedCustomer &&
      setLatlong({
        lat: selectedCustomer.latitude,
        lng: selectedCustomer.longitude,
      });
  }, [selectedCustomer]);
  /* ============================================= || 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);
      setLocations(updatedLocations);
    } catch (err) {
      console.log("locationRes", err);
    }
  };
  useEffect(() => {
    fetchAppLocations();
  }, []);
  /* ============================================= || fetchAllClients| ============================================= */
  const fetchAllClients = async () => {
    setisloader(true);
    try {
      let url = "";
      if (search) {
        url = `${process.env.REACT_APP_URL}/tenants/search/?keyword=${search}&status=${status}`;
      } else {
        url =
          appId == 0
            ? `${process.env.REACT_APP_URL}/tenants/getalltenants/?status=${status}&pageno=${pageno}&pagesize=${rowsPerPage}`
            : `${process.env.REACT_APP_URL}/tenants/getalltenants/?status=${status}&applocationid=${appId}&pageno=${pageno}&pagesize=${rowsPerPage}`;
      }
      const allClientsResponse = await axios.get(url);
      console.log("allClientsResponse", allClientsResponse.data.details);
      setAllClientData(allClientsResponse.data.details);

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

  useEffect(() => {
    fetchAllClients();
  }, [pageno, search, appId, status]);
  useEffect(() => {
    fetchclientpricelist();
  }, [selectedTenid]);
  /* ============================================= || fetchTenanatPricing || ============================================= */
  const fetchTenanatPricing = async (id) => {
    try {
      let tenantPricing = await axios.get(
        `${process.env.REACT_APP_URL}/tenants/gettenantpricing/?tenantid=${id}`
      );
      console.log("tenantPricing", tenantPricing.data.details);
      setTenanatPricing(tenantPricing.data.details);
    } catch (error) {
      console.log("fetchTenanatPricing", error);
    }
  };
  useEffect(() => {
    fetchTenanatPricing(selectedTenid);
  }, [selectedTenid]);
  /* ============================================= || tenantupdate || ============================================= */

  const tenantupdate = async (tenid) => {
    console.log("tenantPricing.baseprice", tenantPricing.baseprice);
    console.log("clientstatus", clientstatus);
    console.log("selectedTenid", selectedTenid);
    console.log("status", status);
    setisloader(true);
    let updateData;
    if (tenid == -1) {
      updateData = {
        tenantid: selectedTenid,
        approved: 1,
      };
    } else {
      updateData = {
        tenantid: tenid,
        status: status === "active" ? "InActive" : "Active",
      };
    }
    await axios
      .put(`${process.env.REACT_APP_URL}/tenants/update`, updateData)
      .then((res) => {
        if (res.data.status) {
          opentoast(
            value0 == 0
              ? "Inactivated Successfully"
              : value0 == 1
              ? "Approved Successfully"
              : "Activate Successfully",
            "success",
            2000
          );
          fetchAllClients();
          setisloader(false);
        }
      })
      .catch((err) => {
        console.log(err);
        opentoast(err.message, "error", 1500);
        setisloader(false);
      });
    // }
  };
  /* ============================================= || getAppPricing || ============================================= */
  const getAppPricing = async (id) => {
    console.log("id", id);
    try {
      let appPricingRes = await axios.get(
        `${process.env.REACT_APP_URL}/utils/getapptypes/?tag=pricing`
      );
      console.log("appPricingRes", appPricingRes.data.details);
      setAppPricing(appPricingRes.data.details);
    } catch (error) {
      console.log("appPricingRes", error);
    }
  };
  /* ============================================= || createpricing || ============================================= */
  const createpricing = async () => {
    setisloader(true);
    await axios
      .post(`${process.env.REACT_APP_URL}/tenants/createpricing`, {
        tenantpricingid: 0,
        applocationid: appId,
        pricingid: selectedPricing.apptypeid,
        tenantid: selectedTenid,
        pricingdate: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        configid: selectedPricing.configid,
        pricingtypeid: selectedPricing.apptypeid,
        slab: selectedPricing.typename,
        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();
          setSelectedPricing({});
          tenantupdate(-1);
          fetchclientpricelist();
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  /* ============================================= || updateClient || ============================================= */
  const updateClient = async () => {
    try {
      const arr = { ...editClient, tenantid: selectedTenid };

      console.log("updateClient", arr);
      const updateRes = await axios.put(
        `${process.env.REACT_APP_URL}/tenants/update`,
        arr
      );
      console.log("updateClient", updateRes.data.message);
      if (updateRes.data.status) {
        opentoast(updateRes.data.message, "success", 1500);
      }
      fetchAllClients();
    } catch (err) {
      console.log("updateClient", err);
    }
  };

  return (
    <div>
      {isloader && <Loader />}
      {/* ========================================================== || Titlecard ||  ========================================================== */}
      <Stack
        direction={"row"}
        justifyContent="space-between"
        alignItems="center"
        sx={{ my: 1 }}
      >
        <TitleCard title="Clients " />
        <Autocomplete
          disablePortal
          id="combo-box-demo"
          options={locations || []}
          getOptionLabel={(option) => `${option.locationname}`}
          sx={{ width: 300, height: "30px", ml: 3, zIndex: "100", mt: -3 }}
          onChange={(event, value, reason) => {
            if (reason === "clear") {
              setAppId(0);
              setLocoName("Select  Locations");
              setPageno(1);
            } else {
              console.log(value);
              setAppId(value.applocationid);
              setLocoName(value.locationname);
              setPageno(1);
            }
          }}
          renderInput={(params) => <TextField {...params} label={locaName} />}
        />{" "}
      </Stack>
      {/* ========================================================== || MainCard (search) ||  ========================================================== */}
      <MainCard
        content={false}
        title={
          <Stack
            minWidth={"100%"}
            flexDirection={{ xs: "column-reverse", sm: "row" }}
            sx={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
            }}
          >
            {/* ============================================= || Tabs  ||  ================================================= */}
            <Box sx={{ width: "100%" }}>
              <Tabs
                value={value0}
                onChange={handleChange}
                aria-label="basic tabs example"
              >
                <Tab
                  label="Active"
                  sx={{ ml: -2 }}
                  onClick={() => {
                    setstatus("active");
                  }}
                />
                <Tab
                  label="Pending"
                  onClick={() => {
                    setstatus("pending");
                  }}
                />
                <Tab
                  label="Inactive"
                  onClick={() => {
                    setstatus("inactive");
                  }}
                />
              </Tabs>
            </Box>
            {/* ============================================= || SearchOutlined  ||  ================================================= */}
            <OutlinedInput
              inputRef={textFieldRef}
              id="input-search-header"
              placeholder="Search (ctrl+k)"
              value={search}
              onChange={(e) => {
                setSearch(e.target.value);
              }}
              sx={{
                mb: { xs: 2, sm: 0 },
                width: "375px",
              }}
              startAdornment={
                <InputAdornment position="start">
                  <SearchOutlined
                    style={{
                      fontSize: "medium",

                      fontWeight: "bolder",
                    }}
                  />
                </InputAdornment>
              }
              endAdornment={
                <IconButton
                  sx={{ visibility: search ? "visible" : "hidden" }}
                  onClick={() => {
                    setSearch("");
                    fetchAllClients();
                  }}
                >
                  <CloseOutlined
                    style={{ fontSize: "medium", color: "#65387A" }}
                  />
                </IconButton>
              }
            />
          </Stack>
        }
      >
        {/* ============================================= || TableContainer| =============================================  */}
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>S.No</TableCell>
                <TableCell>Client</TableCell>
                <TableCell>Contact</TableCell>
                <TableCell>Address</TableCell>
                <TableCell align="center" sx={{ width: 150 }}>
                  Actions
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {allClientsdata.length == 0 ? (
                <TableRow>
                  <TableCell colSpan={6}>
                    <Stack
                      width={"100%"}
                      direction={"row"}
                      justifyContent={"center"}
                    >
                      <Empty />
                    </Stack>
                  </TableCell>
                </TableRow>
              ) : (
                allClientsdata.map((row, index) => (
                  <>
                    {/* ============================================ || tablerow 1 || ============================================ */}
                    <TableRow
                      key={index}
                      sx={{
                        bgcolor:
                          openRowIndex1 === index || openRowIndex2 === index
                            ? "#e1bee7"
                            : null,
                        "&:hover": {
                          bgcolor:
                            openRowIndex1 === index || openRowIndex2 === index
                              ? "#e1bee7!important"
                              : null,
                          cursor: "pointer",
                        },
                      }}
                    >
                      <TableCell>{(pageno - 1) * 10 + index + 1}</TableCell>
                      <TableCell>{row.tenantname}</TableCell>
                      <TableCell>{row.primarycontact}</TableCell>
                      <TableCell>{row.address}</TableCell>
                      <TableCell align="center">
                        <IconButton
                          aria-label="expand row"
                          size="medium"
                          sx={{
                            color:
                              value0 == 1
                                ? theme.palette.primary.main
                                : theme.palette.success.dark,
                          }}
                        >
                          <Tooltip
                            title={
                              value0 == 0
                                ? "Inactive"
                                : value == 1
                                ? "Approve"
                                : "Active"
                            }
                            placement="top"
                          >
                            {value0 == 0 ? (
                              <StopOutlined
                                style={{ color: "red" }}
                                onClick={() => {
                                  setSelectedCustomer(row);
                                  setSelectedtenid(row.tenantid);
                                  setAppId(row.applocationid);
                                  setClientstatus(row.approved);
                                  setTimeout(() => {
                                    tenantupdate(row.tenantid);
                                  }, 100);
                                }}
                              />
                            ) : value0 == 1 ? (
                              <IssuesCloseOutlined
                                onClick={() => {
                                  setSelectedCustomer(row);
                                  setDialogopen(true);
                                  setSelectedtenid(row.tenantid);
                                  setAppId(row.applocationid);
                                  getAppPricing(row.applolcationid);
                                }}
                              />
                            ) : (
                              <FaRegCheckCircle
                                onClick={() => {
                                  setSelectedCustomer(row);
                                  setSelectedtenid(row.tenantid);
                                  setAppId(row.applocationid);
                                  setTimeout(() => {
                                    tenantupdate(row.tenantid);
                                  }, 100);
                                }}
                              />
                            )}
                          </Tooltip>
                        </IconButton>
                        <IconButton
                          aria-label="expand row"
                          size="medium"
                          onClick={() => {
                            setSelectedCustomer(row);
                            handleCollapseToggle1(index); // makes 1st collpase open
                            setOpenRowIndex2(-1); //makes 2nd collapse close , if open
                            setSelectedtenid(row.tenantid);
                            setAppId(row.applocationid);
                          }}
                          sx={{
                            color:
                              openRowIndex1 === index
                                ? theme.palette.error.main
                                : theme.palette.primary.main,
                          }}
                        >
                          <Tooltip
                            title={
                              openRowIndex1 === index ? "Close" : "View Details"
                            }
                            placement="top"
                          >
                            {openRowIndex1 === index ? (
                              <EyeInvisibleOutlined />
                            ) : (
                              <EyeOutlined />
                            )}
                          </Tooltip>
                        </IconButton>
                        {value0 !== 1 && (
                          <IconButton
                            aria-label="expand row"
                            size="medium"
                            onClick={() => {
                              setSelectedCustomer(row);
                              handleCollapseToggle2(index); // makse 2nd collpase open
                              setOpenRowIndex1(-1); // makse 1st collpse close if open
                              setSelectedtenid(row.tenantid);
                              setAppId(row.applocationid);
                            }}
                            sx={{
                              color:
                                openRowIndex2 === index
                                  ? theme.palette.error.main
                                  : theme.palette.primary.main,
                            }}
                          >
                            <Tooltip
                              title={openRowIndex2 === index ? "Close" : "Edit"}
                              placement="top"
                            >
                              {openRowIndex2 === index ? (
                                <CloseOutlined />
                              ) : (
                                <EditOutlined />
                              )}
                            </Tooltip>
                          </IconButton>
                        )}
                      </TableCell>
                    </TableRow>
                    {/* ============================================ || collapsive row  (1) (view) || ============================================ */}
                    {openRowIndex1 === index && (
                      <TableRow
                        sx={{
                          // bgcolor:
                          //   openRowIndex1 === index || openRowIndex2 === index
                          //     ? "#f3e5f5"
                          //     : null,
                          "&:hover": {
                            // bgcolor:
                            //   openRowIndex1 === index || openRowIndex2 === index
                            //     ? "#f3e5f5!important"
                            //     : null,
                            cursor:
                              openRowIndex1 === index || openRowIndex2 === index
                                ? "pointer"
                                : null,
                          },
                        }}
                      >
                        <TableCell
                          style={{ paddingBottom: 0, paddingTop: 0 }}
                          colSpan={15}
                        >
                          <Collapse in={true} timeout="auto" unmountOnExit>
                            <Box sx={{ margin: 1 }}>
                              <Tabs
                                value={value1}
                                onChange={handleChange1}
                                aria-label="basic tabs example"
                              >
                                <Tab
                                  label=" Details"
                                  icon={
                                    <TbBrandDatabricks
                                      style={{
                                        marginRight: 5,
                                        fontSize: "20px",
                                        marginBottom: -1,
                                      }}
                                    />
                                  }
                                  sx={{
                                    alignItems: "center",
                                    flexDirection: "row",
                                  }}
                                />
                                <Tab
                                  label="Pricing"
                                  icon={
                                    <GiMoneyStack
                                      style={{
                                        marginRight: 5,
                                        fontSize: "20px",
                                        marginBottom: -1,
                                      }}
                                    />
                                  }
                                  sx={{
                                    alignItems: "center",
                                    flexDirection: "row",
                                  }}
                                />
                              </Tabs>
                            </Box>
                            {/* ============================================= || Details || ============================================= */}
                            {value1 == 0 && (
                              <Card
                                variant="outlined"
                                key={"left - card"}
                                sx={{ m: 2 }}
                              >
                                <Grid container xs={12} spacing={0}>
                                  <Grid item xs={4}>
                                    <Card
                                      variant="outlined"
                                      sx={{
                                        height: "100%",
                                        alignItems: "center",
                                        // bgcolor: "#f3e5f5",
                                      }}
                                    >
                                      <CardHeader
                                        avatar={
                                          <FaRegCircleUser
                                            style={{ fontSize: "40px" }}
                                          />
                                        }
                                        title={
                                          <Typography variant="h5">
                                            {row.tenantname}
                                          </Typography>
                                        }
                                        subheader={
                                          <Typography>
                                            {row.registrationno}
                                          </Typography>
                                        }
                                        sx={{
                                          flexDirection: "column",
                                          gap: "20px",
                                          alignItems: "center",
                                          textAlign: "center",
                                          m: 3,
                                        }}
                                      />
                                      <Divider />
                                      <CardHeader
                                        sx={{
                                          display: "flex",
                                          flexDirection: "row",
                                          alignItems: "center",
                                          alignContent: "center",
                                        }}
                                        avatar={
                                          <LuMail
                                            style={{ fontSize: "20px" }}
                                          />
                                        }
                                        subheader={
                                          <Typography>
                                            {row.primarycontact}
                                          </Typography>
                                        }
                                      />
                                      <CardHeader
                                        avatar={
                                          <FiPhoneCall
                                            style={{ fontSize: "20px" }}
                                          />
                                        }
                                        subheader={
                                          <Typography>
                                            {row.primaryemail}
                                          </Typography>
                                        }
                                      />
                                    </Card>
                                  </Grid>
                                  <Grid item xs={8}>
                                    <Card
                                      variant="outlined"
                                      // sx={{ bgcolor: "#f3e5f5" }}
                                    >
                                      <CardHeader
                                        avatar={
                                          <TbListDetails
                                            style={{
                                              fontSize: "20px",
                                            }}
                                          />
                                        }
                                        title={
                                          <Typography variant="h5">
                                            Contact Details
                                          </Typography>
                                        }
                                      />
                                      <Divider />
                                      <CardContent>
                                        <Grid
                                          container
                                          spacing={2.5}
                                          alignItems="center"
                                        >
                                          <Grid item xs={12}>
                                            <Grid
                                              container
                                              spacing={4}
                                              alignItems="center"
                                            >
                                              <Grid item>
                                                <FiUser
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <Typography align="left">
                                                  {row.firstname}
                                                </Typography>
                                                <Typography
                                                  align="left"
                                                  variant="caption"
                                                  color="secondary"
                                                >
                                                  Contact Person
                                                </Typography>
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                          <Grid item xs={12}>
                                            <Grid
                                              container
                                              spacing={4}
                                              alignItems="center"
                                            >
                                              <Grid item>
                                                <FaRegAddressCard
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <Typography align="left">
                                                  {row.address}
                                                </Typography>
                                                <Typography
                                                  align="left"
                                                  variant="caption"
                                                  color="secondary"
                                                >
                                                  Address
                                                </Typography>
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                          <Grid item xs={12}>
                                            <Grid
                                              container
                                              spacing={4}
                                              alignItems="center"
                                            >
                                              <Grid item>
                                                <TbCategoryMinus
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <Typography align="left">
                                                  {row.subcategoryname}
                                                </Typography>
                                                <Typography
                                                  align="left"
                                                  variant="caption"
                                                  color="secondary"
                                                >
                                                  Category
                                                </Typography>
                                              </Grid>
                                              <Grid item>
                                                <MdMyLocation
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <Typography
                                                  align="left"
                                                  variant="subtitle1"
                                                >
                                                  {row.suburb}
                                                </Typography>
                                                <Typography
                                                  align="left"
                                                  variant="caption"
                                                  color="secondary"
                                                >
                                                  Location
                                                </Typography>
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                          <Grid item xs={12}>
                                            <Grid
                                              container
                                              spacing={4}
                                              alignItems="center"
                                            >
                                              <Grid item>
                                                <GiModernCity
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <Typography align="left">
                                                  {row.city}
                                                </Typography>
                                                <Typography
                                                  align="left"
                                                  variant="caption"
                                                  color="secondary"
                                                >
                                                  City
                                                </Typography>
                                              </Grid>
                                              <Grid item>
                                                <MdNumbers
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <Typography
                                                  align="left"
                                                  variant="subtitle1"
                                                >
                                                  {row.postcode}
                                                </Typography>
                                                <Typography
                                                  align="left"
                                                  variant="caption"
                                                  color="secondary"
                                                >
                                                  PostCode
                                                </Typography>
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                          <Grid item xs={12}>
                                            <Grid
                                              container
                                              spacing={4}
                                              alignItems="center"
                                            >
                                              <Grid item>
                                                <TbWorldLatitude
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <Typography align="left">
                                                  {row.latitude}
                                                </Typography>
                                                <Typography
                                                  align="left"
                                                  variant="caption"
                                                  color="secondary"
                                                >
                                                  Latitude
                                                </Typography>
                                              </Grid>
                                              <Grid item>
                                                <TbWorldLongitude
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <Typography
                                                  align="left"
                                                  variant="subtitle1"
                                                >
                                                  {row.longitude}
                                                </Typography>
                                                <Typography
                                                  align="left"
                                                  variant="caption"
                                                  color="secondary"
                                                >
                                                  Longitude
                                                </Typography>
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                        </Grid>
                                      </CardContent>
                                    </Card>
                                  </Grid>
                                </Grid>
                              </Card>
                            )}
                            {/* ============================================= || Pricing || ============================================= */}
                            {value1 == 1 && (
                              <Card
                                variant="outlined"
                                key={"left - card"}
                                sx={{ m: 2, bgcolor: "#f3e5f5" }}
                              >
                                <TableContainer>
                                  <Table>
                                    <TableHead>
                                      <TableRow
                                        sx={{ bgcolor: "#e1bee7!important" }}
                                      >
                                        <TableCell>#</TableCell>
                                        <TableCell>Date</TableCell>
                                        <TableCell>Slab</TableCell>
                                        <TableCell align="center">
                                          Base Price
                                        </TableCell>
                                        <TableCell align="center">
                                          Min Kms
                                        </TableCell>
                                        <TableCell align="center">
                                          Price/Km
                                        </TableCell>
                                        <TableCell align="center">
                                          MaxKm
                                        </TableCell>

                                        <TableCell>Other Charges</TableCell>
                                      </TableRow>
                                    </TableHead>
                                    <TableBody>
                                      {clientpricelist.map((val, i) => {
                                        return (
                                          <>
                                            <TableRow
                                              sx={{
                                                bgcolor: "white!important",
                                              }}
                                            >
                                              <TableCell>{i + 1}</TableCell>
                                              <TableCell>
                                                {dayjs(val.pricingdate).format(
                                                  "DD-MM-YYYY"
                                                )}
                                              </TableCell>
                                              <TableCell>{val.slab}</TableCell>
                                              <TableCell align="center">
                                                <Chip
                                                  size="small"
                                                  color="primary"
                                                  label={formatNumberToRupees(
                                                    val.baseprice
                                                  )}
                                                />
                                              </TableCell>
                                              <TableCell align="center">
                                                <Chip
                                                  size="small"
                                                  color="warning"
                                                  label={formatNumberToRupees(
                                                    val.minkm
                                                  )}
                                                />
                                              </TableCell>
                                              <TableCell align="center">
                                                <Chip
                                                  size="small"
                                                  color="success"
                                                  label={formatNumberToRupees(
                                                    val.priceperkm
                                                  )}
                                                />
                                              </TableCell>
                                              <TableCell align="center">
                                                <Chip
                                                  size="small"
                                                  color="error"
                                                  label={formatNumberToRupees(
                                                    val.maxkm
                                                  )}
                                                />
                                              </TableCell>
                                              <TableCell>
                                                {val.othercharges}
                                              </TableCell>
                                            </TableRow>
                                          </>
                                        );
                                      })}
                                    </TableBody>
                                  </Table>
                                </TableContainer>
                              </Card>
                            )}
                          </Collapse>
                        </TableCell>
                      </TableRow>
                    )}
                    {/* ============================================ || collapsive row (2) (edit)|| ============================================ */}
                    {openRowIndex2 === index && (
                      <TableRow
                        sx={{
                          bgcolor:
                            openRow1 === row.tenantname ? "#f3e5f5" : null,
                          "&:hover": {
                            bgcolor:
                              openRow1 === row.tenantname
                                ? "#f3e5f5!important"
                                : null,
                          },
                          cursor:
                            openRow1 === row.tenantname ? "pointer" : null,
                        }}
                      >
                        <TableCell
                          style={{ paddingBottom: 0, paddingTop: 0 }}
                          colSpan={15}
                        >
                          <Collapse in={true} timeout="auto" unmountOnExit>
                            <Box
                              sx={{
                                margin: 1,
                                display: "flex",
                                justifyContent: "space-between",
                                alignItems: "center",
                              }}
                            >
                              <Tabs
                                value={value2}
                                onChange={handleChange2}
                                aria-label="basic tabs example"
                              >
                                <Tab label="Edit Details" />
                                {value0 !== 1 && (
                                  <Tab
                                    label="Edit Pricing"
                                    onClick={() => {
                                      getAppPricing(
                                        selectedCustomer.applolcationid
                                      );
                                    }}
                                  />
                                )}
                              </Tabs>
                              {value2 == 1 && (
                                <Button
                                  variant="contained"
                                  color={"error"}
                                  size="smaller"
                                  startIcon={<EditOutlined size={"small"} />}
                                  sx={{
                                    mr: 1.8,
                                    height: "30px",
                                  }}
                                  onClick={() => {
                                    setDialogopen(true);
                                  }}
                                >
                                  Add Pricing
                                </Button>
                              )}
                            </Box>
                            {/* ============================================= || Edit Details || ============================================= */}
                            {value2 == 0 && (
                              <Card
                                variant="outlined"
                                key={"left - card"}
                                sx={{ m: 2 }}
                              >
                                <Grid container spacing={0}>
                                  <Grid item xs={4}>
                                    <Card
                                      variant="outlined"
                                      sx={{
                                        height: "100%",
                                      }}
                                    >
                                      {/* =========================|| Edit Details (left)|| =========================*/}
                                      <>
                                        <Stack
                                          sx={{
                                            display: "flex",
                                            alignItems: "center",
                                            mt: 3,
                                            mb: 1,
                                          }}
                                        >
                                          <PiUsersThree
                                            style={{ fontSize: "70px" }}
                                          />
                                        </Stack>
                                        <Divider />
                                        <CardHeader
                                          sx={{
                                            display: "flex",
                                            flexDirection: "row",
                                            alignItems: "center",
                                            alignContent: "center",
                                          }}
                                          avatar={
                                            <BiUser
                                              style={{ fontSize: "20px" }}
                                            />
                                          }
                                          subheader={
                                            <TextField
                                              fullWidth
                                              id="outlined-basic"
                                              label={"Client"}
                                              defaultValue={
                                                selectedCustomer.tenantname
                                              }
                                              variant="outlined"
                                              onChange={(e) => {
                                                setEditClient({
                                                  ...editClient,
                                                  tenantname: e.target.value,
                                                });
                                              }}
                                            />
                                          }
                                        />
                                        <CardHeader
                                          sx={{
                                            display: "flex",
                                            flexDirection: "row",
                                            alignItems: "center",
                                            alignContent: "center",
                                          }}
                                          avatar={
                                            <BiRegistered
                                              style={{ fontSize: "20px" }}
                                            />
                                          }
                                          subheader={
                                            <TextField
                                              fullWidth
                                              id="outlined-basic"
                                              label={"Register No"}
                                              defaultValue={row.registrationno}
                                              variant="outlined"
                                              onChange={(e) => {
                                                setEditClient({
                                                  ...editClient,
                                                  registrationno:
                                                    e.target.value,
                                                });
                                              }}
                                              sx={{}}
                                            />
                                          }
                                        />

                                        <Divider />
                                        <CardHeader
                                          sx={{
                                            display: "flex",
                                            flexDirection: "row",
                                            alignItems: "center",
                                            alignContent: "center",
                                          }}
                                          avatar={
                                            <LuMail
                                              style={{ fontSize: "20px" }}
                                            />
                                          }
                                          subheader={
                                            <TextField
                                              fullWidth
                                              id="outlined-basic"
                                              label={"Phone"}
                                              defaultValue={row.primarycontact}
                                              variant="outlined"
                                              onChange={(e) => {
                                                setEditClient({
                                                  ...editClient,
                                                  primarycontact:
                                                    e.target.value,
                                                });
                                              }}
                                              sx={{}}
                                            />
                                          }
                                        />
                                        <CardHeader
                                          avatar={
                                            <FiPhoneCall
                                              style={{ fontSize: "20px" }}
                                            />
                                          }
                                          subheader={
                                            <TextField
                                              fullWidth
                                              id="outlined-basic"
                                              label={"E-mail"}
                                              defaultValue={row.primaryemail}
                                              variant="outlined"
                                              onChange={(e) => {
                                                setEditClient({
                                                  ...editClient,
                                                  primaryemail: e.target.value,
                                                });
                                              }}
                                              sx={{}}
                                            />
                                          }
                                        />
                                      </>
                                    </Card>
                                  </Grid>
                                  {/* =========================|| Edit Details (right) || =========================*/}
                                  <Grid item xs={8}>
                                    <Card variant="outlined">
                                      <CardHeader
                                        avatar={
                                          <TbListDetails
                                            style={{
                                              fontSize: "20px",
                                            }}
                                          />
                                        }
                                        title={
                                          <Typography variant="h5">
                                            Contact Details
                                          </Typography>
                                        }
                                      />
                                      <Divider />

                                      <CardContent>
                                        <Grid
                                          container
                                          spacing={2.5}
                                          alignItems="center"
                                        >
                                          {/* =========================|| contact person || =========================*/}

                                          <Grid item xs={12}>
                                            <Grid
                                              container
                                              spacing={4}
                                              alignItems="center"
                                            >
                                              <Grid item>
                                                <FiUser
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  fullWidth
                                                  id="outlined-basic"
                                                  label={"Contact Person"}
                                                  defaultValue={row.firstname}
                                                  variant="outlined"
                                                  onChange={(e) => {
                                                    setEditClient({
                                                      ...editClient,
                                                      firstname: e.target.value,
                                                    });
                                                  }}
                                                  sx={{ mt: 2 }}
                                                />
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                          {/* =========================|| Address || =========================*/}

                                          <Grid item xs={12}>
                                            <Grid
                                              container
                                              spacing={4}
                                              alignItems="center"
                                            >
                                              <Grid item>
                                                <FaRegAddressCard
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <Autocomplete
                                                  id="google-map-demo"
                                                  fullWidth
                                                  label={"Address"}
                                                  getOptionLabel={(option) =>
                                                    typeof option === "string"
                                                      ? option
                                                      : option.description
                                                  }
                                                  filterOptions={(x) => x}
                                                  options={options}
                                                  autoComplete
                                                  includeInputInList
                                                  filterSelectedOptions
                                                  defaultValue={
                                                    selectedCustomer.address
                                                  }
                                                  noOptionsText="No locations"
                                                  onChange={(
                                                    event,
                                                    newValue
                                                  ) => {
                                                    setOptions(
                                                      newValue
                                                        ? [newValue, ...options]
                                                        : options
                                                    );
                                                    setValue(newValue);
                                                    console.log(
                                                      "newValue",
                                                      newValue
                                                    );
                                                    setAddress(
                                                      newValue.description
                                                    );
                                                    setEditClient({
                                                      ...editClient,
                                                      address:
                                                        newValue.description,
                                                    });
                                                  }}
                                                  onInputChange={(
                                                    event,
                                                    newInputValue
                                                  ) => {
                                                    setInputValue(
                                                      newInputValue
                                                    );
                                                  }}
                                                  renderInput={(params) => (
                                                    <TextField
                                                      {...params}
                                                      fullWidth
                                                      label="Address"
                                                      variant="outlined"
                                                    />
                                                  )}
                                                  renderOption={(
                                                    props,
                                                    option
                                                  ) => {
                                                    const matches =
                                                      option
                                                        .structured_formatting
                                                        .main_text_matched_substrings ||
                                                      [];

                                                    const parts = parse(
                                                      option
                                                        .structured_formatting
                                                        .main_text,
                                                      matches.map((match) => [
                                                        match.offset,
                                                        match.offset +
                                                          match.length,
                                                      ])
                                                    );

                                                    return (
                                                      <li {...props}>
                                                        <Grid
                                                          container
                                                          alignItems="center"
                                                        >
                                                          <Grid
                                                            item
                                                            sx={{
                                                              display: "flex",
                                                              width: 44,
                                                            }}
                                                          >
                                                            <LocationOnIcon
                                                              sx={{
                                                                color:
                                                                  "text.secondary",
                                                              }}
                                                            />
                                                          </Grid>
                                                          <Grid
                                                            item
                                                            sx={{
                                                              width:
                                                                "calc(100% - 44px)",
                                                              wordWrap:
                                                                "break-word",
                                                            }}
                                                          >
                                                            {parts.map(
                                                              (part, index) => (
                                                                <Box
                                                                  key={index}
                                                                  component="span"
                                                                  sx={{
                                                                    fontWeight:
                                                                      part.highlight
                                                                        ? "bold"
                                                                        : "regular",
                                                                  }}
                                                                >
                                                                  {part.text}
                                                                </Box>
                                                              )
                                                            )}
                                                            <Typography
                                                              variant="body2"
                                                              color="text.secondary"
                                                            >
                                                              {
                                                                option
                                                                  .structured_formatting
                                                                  .secondary_text
                                                              }
                                                            </Typography>
                                                          </Grid>
                                                        </Grid>
                                                      </li>
                                                    );
                                                  }}
                                                />
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                          {/* =========================|| category name || =========================*/}

                                          <Grid item xs={12}>
                                            <Grid
                                              container
                                              spacing={4}
                                              alignItems="center"
                                            >
                                              <Grid item>
                                                <TbCategoryMinus
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  fullWidth
                                                  required
                                                  id="outlined-required"
                                                  label="Category"
                                                  defaultValue={
                                                    row.subcategoryname
                                                  }
                                                  onChange={(e) => {
                                                    setEditClient({
                                                      ...editClient,
                                                      subcategoryname:
                                                        e.target.value,
                                                    });
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item>
                                                <MdMyLocation
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  fullWidth
                                                  required
                                                  id="outlined-required"
                                                  label="Location"
                                                  onChange={(e) => {
                                                    setEditClient({
                                                      ...editClient,
                                                      suburb: e.target.value,
                                                    });
                                                  }}
                                                  value={
                                                    suburb == ""
                                                      ? selectedCustomer.suburb
                                                      : suburb
                                                  }
                                                />
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                          {/* =========================|| city || =========================*/}

                                          <Grid item xs={12}>
                                            <Grid
                                              container
                                              spacing={4}
                                              alignItems="center"
                                            >
                                              <Grid item>
                                                <GiModernCity
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  fullWidth
                                                  required
                                                  id="outlined-required"
                                                  label="City"
                                                  onChange={(e) => {
                                                    setEditClient({
                                                      ...editClient,
                                                      city: e.target.value,
                                                    });
                                                  }}
                                                  value={
                                                    city == ""
                                                      ? selectedCustomer.city
                                                      : city
                                                  }
                                                />
                                              </Grid>
                                              <Grid item>
                                                <MdNumbers
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  fullWidth
                                                  required
                                                  label=" PostCode"
                                                  id="outlined-required"
                                                  onChange={(e) => {
                                                    {
                                                      setEditClient({
                                                        ...editClient,
                                                        postcode:
                                                          e.target.value,
                                                      });
                                                    }
                                                  }}
                                                  value={
                                                    zipcode == ""
                                                      ? selectedCustomer.postcode
                                                      : zipcode
                                                  }
                                                />
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                          {/* =========================|| latitude || =========================*/}

                                          <Grid item xs={12}>
                                            <Grid
                                              container
                                              spacing={4}
                                              alignItems="center"
                                            >
                                              <Grid item>
                                                <TbWorldLatitude
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  variant="outlined"
                                                  readonly
                                                  label="Latitude"
                                                  fullWidth
                                                  value={latlong.lat}
                                                  sx={{ cursor: "not-allowed" }}
                                                  // onChange={(e) => {
                                                  //   setLati(e.target.value.toString())
                                                  //   setEditClient({
                                                  //     ...editClient,
                                                  //     latitude:
                                                  //       latlong.lat.toString(),
                                                  //   });
                                                  // }}
                                                />
                                              </Grid>
                                              <Grid item>
                                                <TbWorldLongitude
                                                  style={{
                                                    fontSize: "20px",
                                                    fontWeight: "lighter",
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  label="Longitude"
                                                  readonly
                                                  variant="outlined"
                                                  fullWidth
                                                  value={latlong.lng}
                                                  // onChange={(e) => {
                                                  //   setLongi(e.target.value.toString())
                                                  //   setEditClient({
                                                  //     ...editClient,
                                                  //     longitude:
                                                  //       e.target.value.toString(),
                                                  //   });
                                                  // }}
                                                />
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                        </Grid>
                                      </CardContent>
                                      {/* =========================|| update || =========================*/}

                                      <CardActions
                                        sx={{
                                          display: "flex",
                                          justifyContent: "end",
                                          mr: 3,
                                          mb: 2,
                                        }}
                                      >
                                        <Button
                                          variant="contained"
                                          size="medium"
                                          onClick={() => {
                                            updateClient();
                                          }}
                                        >
                                          Update Client
                                        </Button>
                                      </CardActions>
                                    </Card>
                                  </Grid>
                                </Grid>
                              </Card>
                            )}
                            {/* ============================================= || Edit Pricing || ============================================= */}
                            {value2 == 1 && (
                              <Card
                                variant="outlined"
                                key={"left - card"}
                                sx={{ m: 2, bgcolor: "#f3e5f5" }}
                              >
                                <TableContainer>
                                  <Table>
                                    <TableHead>
                                      <TableRow
                                        sx={{ bgcolor: "#e1bee7!important" }}
                                      >
                                        <TableCell>#</TableCell>
                                        <TableCell>Date</TableCell>
                                        <TableCell>Slab</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
                                              sx={{
                                                bgcolor: "white!important",
                                              }}
                                            >
                                              <TableCell>{i + 1}</TableCell>
                                              <TableCell>
                                                {dayjs(val.pricingdate).format(
                                                  "DD-MM-YYYY"
                                                )}
                                              </TableCell>
                                              <TableCell>{val.slab}</TableCell>
                                              <TableCell>
                                                {val.baseprice}
                                              </TableCell>
                                              <TableCell>{val.minkm}</TableCell>
                                              <TableCell>
                                                {val.priceperkm}
                                              </TableCell>
                                              <TableCell>
                                                {val.othercharges}
                                              </TableCell>
                                            </TableRow>
                                          </>
                                        );
                                      })}
                                    </TableBody>
                                  </Table>
                                </TableContainer>
                              </Card>
                            )}
                          </Collapse>
                        </TableCell>
                      </TableRow>
                    )}
                  </>
                ))
              )}
            </TableBody>
          </Table>
        </TableContainer>
        <Divider />
        {/* ============================================= || Pagination| =============================================  */}
        <Box sx={{ width: "100%", px: 2, py: 1.2, bgcolor: "#f3e5f5" }}>
          <Grid container>
            <Grid item xs={12}>
              <Stack
                direction={"row"}
                justifyContent={"flex-end"}
                alignItems={"center"}
                spacing={1}
              >
                <IconButton
                  disabled={pageno <= 1}
                  color="primary"
                  size="medium"
                  onClick={() => {
                    setPageno((prev) => prev - 1);
                  }}
                >
                  <LeftOutlined />
                </IconButton>
                <Typography
                  variant="h5"
                  color={"primary"}
                  sx={{
                    border: `1px solid ${theme.palette.primary.light}`,
                    px: 1,
                    borderRadius: "5px",
                  }}
                >
                  {pageno}
                </Typography>
                <IconButton
                  disabled={allClientsdata.length < rowsPerPage}
                  color="primary"
                  size="medium"
                  onClick={() => {
                    setPageno((prev) => prev + 1);
                  }}
                >
                  <RightOutlined />
                </IconButton>
              </Stack>
            </Grid>
          </Grid>
        </Box>
      </MainCard>
      {/* // ==============================||( 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  - (${selectedCustomer.tenantname})`}
        </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.typename}`}
                  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={!isPrice ? selectedPricing.baseprice : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      baseprice: e.target.value,
                    });
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Price/Km</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={!isPrice ? selectedPricing.priceperkm : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      priceperkm: e.target.value,
                    });
                  }}
                />
              </Grid>

              <Grid item xs={12} sm={6}>
                <FormLabel>Min Kms</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={!isPrice ? selectedPricing.minkm : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      minkm: e.target.value,
                    });
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Max Kms</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={!isPrice ? selectedPricing.maxkm : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      maxkm: e.target.value,
                    });
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Min Orders</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={!isPrice ? selectedPricing.minorder : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      minorder: e.target.value,
                    });
                  }}
                />
              </Grid>
            </Grid>
          </MainCard>
        </DialogContent>
        <DialogActions>
          <Grid container>
            <Grid item xs={12}>
              <Stack
                direction={"row"}
                justifyContent={"flex-end"}
                spacing={2}
                sx={{ p: 2 }}
              >
                {value2 == 1 && (
                  <Button
                    disabled={isPrice}
                    variant="contained"
                    onClick={() => {
                      createpricing();
                    }}
                  >
                    Update Pricing
                  </Button>
                )}
                {value0 == 1 && (
                  <Button
                    disabled={isPrice}
                    variant="contained"
                    onClick={() => {
                      createpricing();
                    }}
                  >
                    Save
                  </Button>
                )}
                <Button
                  variant="contained"
                  onClick={() => {
                    setIsprice(true);
                    setTimeout(() => {
                      dialogclose();
                    }, 100);
                    setSelectedPricing({});
                  }}
                  color="error"
                >
                  Cancel
                </Button>
              </Stack>
            </Grid>
          </Grid>
        </DialogActions>
      </Dialog>
    </div>
  );
};

export default Clients;
