import PropTypes from "prop-types";
import { React, useState, useEffect, useRef, useMemo } from "react";
import TitleCard from "pages/titleCard";

import { useQuery } from "@tanstack/react-query";
import { fetchCustomersList, fetchCustomersListBySearch } from "pages/api/api";
import { Empty } from "antd";
import axios from "axios";
import { FaRegEdit } from "react-icons/fa";
import { RiEdit2Fill } from "react-icons/ri";
import { enqueueSnackbar } from "notistack";

import { styled, useTheme } from "@mui/material/styles";
// material-ui
import {
  Box,
  Checkbox,
  Divider,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableSortLabel,
  TableRow,
  Grid,
  Typography,
  OutlinedInput,
  InputAdornment,
  IconButton,
  Stack,
  Tooltip,
  Dialog,
  DialogActions,
  DialogTitle,
  DialogContent,
  DialogContentText,
  Button,
  TextField,
  Autocomplete,
} from "@mui/material";
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 { SearchOutlined, LeftOutlined, RightOutlined } from "@ant-design/icons";
import ClearIcon from "@mui/icons-material/Clear";

import { visuallyHidden } from "@mui/utils";

// project imports
import MainCard from "components/MainCard";
import {
  // CSVExport,
  TableRowSelection,
} from "components/third-party/ReactTable";
import Loader from "components/Loader";
import InputLabel from "themes/overrides/InputLabel";

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

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

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

// table header cells
const headCells = [
  {
    id: "name",
    numeric: false,
    disablePadding: true,
    label: "Name",
  },

  {
    id: "address",
    numeric: false,
    disablePadding: false,
    label: "Address",
  },
  {
    id: "location",
    numeric: false,
    disablePadding: false,
    label: "Location",
  },
  {
    id: "action",
    numeric: "center",
    disablePadding: false,
    label: "Action",
  },
];

// ==============================|| MUI TABLE - HEADER ||============================== //

function EnhancedTableHead({
  onSelectAllClick,
  order,
  orderBy,
  numSelected,
  rowCount,
  onRequestSort,
}) {
  const createSortHandler = (property) => (event) => {
    onRequestSort(event, property);
  };

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

// ==============================|| MUI TABLE - ENHANCED ||============================== //

export default function Customers() {
  const [rows, setRows] = useState([]);
  const [order, setOrder] = useState("asc");
  const [orderBy, setOrderBy] = useState("calories");
  const [selected, setSelected] = useState([]);
  const [dense] = useState(false);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [selectedValue, setSelectedValue] = useState([]);
  const [pages, setPages] = useState(1);
  const [search, setSearch] = useState("");
  const [filteredList, setFilteredList] = useState([]);
  const [isloader, setisloader] = useState(true);
  const [selectedCustomer, setSelectedCustomer] = useState({}); // to edit
  const theme = useTheme();
  const textFieldRef = useRef(null);
  const [open, setOpen] = useState(false);
  const [address, setAddress] = useState("");
  const [latlong, setLatlong] = useState({});
  // ==============================|| for google address ||============================== //
  const [value, setValue] = 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,
            });
            setSelectedCustomer({
              ...selectedCustomer,
              latitude: lat,
              longitude: lng,
            });
            console.log("address", response);
            let city1, zipcode1, state1, suburb1;

            for (
              let i = 0;
              i < response.results[0].address_components.length;
              i++
            ) {
              for (
                let j = 0;
                j < response.results[0].address_components[i].types.length;
                j++
              ) {
                switch (response.results[0].address_components[i].types[j]) {
                  case "locality":
                    city1 = response.results[0].address_components[i].long_name;
                    break;
                  case "administrative_area_level_1":
                    state1 =
                      response.results[0].address_components[i].long_name;
                    break;
                  case "postal_code":
                    zipcode1 =
                      response.results[0].address_components[i].long_name;
                    break;
                  case "sublocality":
                    suburb1 =
                      response.results[0].address_components[i].long_name;
                    break;
                }
              }
            }
            setSelectedCustomer({
              ...selectedCustomer,
              suburb: suburb1,
              city: city1,
              state: state1,
              postcode: zipcode1,
            });
            console.log({ city1, zipcode1, state1, suburb1 });
            console.log(latlong);
          }
        },
        (error) => {
          console.log(error);
        }
      );
    } catch (err) {
      console.log(err);
    }
  }, [address]);

  // ==============================|| for dialog ||============================== //

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  /* ============================================= || 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);
    };
  }, []);

  // ==============================|| fetchCustomersList (customers) ||============================== //
  const fetchCustomersList = async () => {
    setisloader(true);
    try {
      let customerResponse = await axios.get(
        `${process.env.REACT_APP_URL}/customers/getallcustomers/?pageno=${pages}&pagesize=10`
      );
      console.log("customerResponse", customerResponse.data.details);
      setRows(customerResponse.data.details);
      setisloader(false);
    } catch (error) {
      console.log("fetchCustomersList", error);
    }
  };
  // ==============================|| fetchCustomersListBySearch (customers)||============================== //
  const fetchCustomersListBySearch = async () => {
    setisloader(true);
    try {
      let searchResponse = await axios.get(
        `${process.env.REACT_APP_URL}/customers/search/?keyword=${search}`
      );
      console.log("searchResponse", searchResponse.data.details);
      setRows(searchResponse.data.details);
      setisloader(false);
    } catch (error) {
      console.log("fetchCustomersListBySearch", error);
    }
  };
  useEffect(() => {
    fetchCustomersList();
  }, [pages]);

  useEffect(() => {
    search.length > 3 && fetchCustomersListBySearch();
    search == "" && fetchCustomersList();
  }, [search]);

  const handleRequestSort = (event, property) => {
    const isAsc = orderBy === property && order === "asc";
    setOrder(isAsc ? "desc" : "asc");
    setOrderBy(property);
  };

  const handleSelectAllClick = (event) => {
    if (event.target.checked) {
      const newSelectedId = rows.map((n) => n.name);
      setSelected(newSelectedId);
      return;
    }
    setSelected([]);
  };

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

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

  const handleSearch = (value) => {
    if (value == "") {
      setPages(1);
    }
  };
  useEffect(() => {
    console.log("selectedCustomer", selectedCustomer);
  }, [selectedCustomer]);

  const openToast = (message, variant, duration) => {
    enqueueSnackbar(message, {
      variant: variant,
      anchorOrigin: { vertical: "top", horizontal: "right" },
      autoHideDuration: duration,
    });
  };
  // ==============================|| updateCustomer (post)||============================== //
  const updateCustomer = async () => {
    if (!selectedCustomer.firstname) {
      openToast("Enter Door NO", "warning", 1500);
    } else if (!selectedCustomer.contactno) {
      openToast("Enter Contact Number ", "warning", 1500);
    } else if (!selectedCustomer.address) {
      openToast("Enter Valid Address", "warning", 1500);
    } else if (!selectedCustomer.doorno) {
      openToast("Enter Door Number ", "warning", 1500);
    } else if (!selectedCustomer.suburb) {
      openToast("Enter Suburb", "warning", 1500);
    } else if (!selectedCustomer.city) {
      openToast("Enter City ", "warning", 1500);
    } else if (!selectedCustomer.state) {
      openToast("Enter State", "warning", 1500);
    } else if (!selectedCustomer.postcode) {
      openToast("Enter PostCode", "warning", 1500);
    } else if (!selectedCustomer.landmark) {
      openToast("Enter Landmark", "warning", 1500);
    } else if (!selectedCustomer.latitude) {
      openToast("Enter Latitude", "warning", 1500);
    } else if (!selectedCustomer.longitude) {
      openToast("Enter Longitude", "warning", 1500);
    } else {
      try {
        const postUpdateResponse = await axios.put(
          `${process.env.REACT_APP_URL}/customers/update`,
          {
            customerid: selectedCustomer.customerid,
            configid: 1,
            firstname: selectedCustomer.firstname,
            applocationid: selectedCustomer.applocationid,
            profileimage: "",
            dialcode: "+91",
            contactno: selectedCustomer.contactno,
            devicetype: "",
            deviceid: "",
            customertoken: "123",
            address: selectedCustomer.address,
            suburb: selectedCustomer.suburb,
            city: selectedCustomer.city,
            state: selectedCustomer.state,
            postcode: selectedCustomer.postcode,
            landmark: selectedCustomer.landmark,
            doorno: selectedCustomer.doorno,
            latitude: selectedCustomer.latitude.toString(),
            longitude: selectedCustomer.longitude.toString(),
          }
        );

        console.log("postUpdateResponse", postUpdateResponse);
        if (postUpdateResponse.data.status) {
          openToast(postUpdateResponse.data.message, "success", 1500);
          handleClose();
          fetchCustomersList();
        }
      } catch (error) {
        console.log("postUpdate error", error);
      }
    }
  };
  return (
    <>
      {isloader && <Loader />}
      <TitleCard title="Customers " />{" "}
      <MainCard
        content={false}
        title="Customers Details"
        sx={{ mt: "10px" }}
        secondary={
          <>
            <OutlinedInput
              inputRef={textFieldRef}
              id="input-search-header"
              placeholder="Search (ctrl+k)"
              value={search}
              onChange={(e) => {
                setSearch(e.target.value);
                // handleSearch(e.target.value);
              }}
              sx={{
                "& .MuiOutlinedInput-input": {
                  p: "1.5px 0px 1px",
                },
                width: "100%",
              }}
              //   style={{ margin: "15px 20px" }}
              startAdornment={
                <InputAdornment position="start">
                  <SearchOutlined
                    style={{
                      fontSize: "medium",
                      // color: !disableSearchFeild ? "#65387A" : "grey",
                      fontWeight: "bolder",
                    }}
                  />
                </InputAdornment>
              }
              endAdornment={
                <IconButton
                  sx={{ visibility: search ? "visible" : "hidden" }}
                  onClick={() => {
                    setSearch("");
                    setPages(1);
                    fetchCustomersList();
                  }}
                >
                  <ClearIcon style={{ fontSize: "medium", color: "#65387A" }} />
                </IconButton>
              }
            />
          </>
        }
      >
        <TableRowSelection selected={selected.length} />
        {/* table */}
        <TableContainer>
          <Table
            sx={{ minWidth: 750 }}
            aria-labelledby="tableTitle"
            size={dense ? "small" : "medium"}
          >
            <EnhancedTableHead
              numSelected={selected.length}
              order={order}
              orderBy={orderBy}
              onSelectAllClick={handleSelectAllClick}
              onRequestSort={handleRequestSort}
              // rowCount={rows.length}
            />

            <TableBody>
              {/* {stableSort(rows, getComparator(order, orderBy))
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) */}

              {rows.length == 0 ? (
                <>
                  <TableCell colSpan={6}>
                    <Stack
                      width={"100%"}
                      direction={"row"}
                      justifyContent={"center"}
                    >
                      <Empty />
                    </Stack>
                  </TableCell>
                </>
              ) : (
                rows
                  // .filter(
                  //   (item) =>
                  //     item.firstname
                  //       .toLowerCase()
                  //       .includes(search.toLowerCase()) ||
                  //     item.contactno.toLowerCase().includes(search.toLowerCase())
                  // )
                  .map((row, index) => {
                    if (typeof row === "number") return null;
                    const isItemSelected = isSelected(row.name);
                    const labelId = `enhanced-table-checkbox-${index}`;
                    return (
                      <TableRow
                        hover
                        role="checkbox"
                        aria-checked={isItemSelected}
                        tabIndex={-1}
                        key={row.name}
                        selected={isItemSelected}
                      >
                        {/* <TableCell sx={{ pl: 3 }} padding="checkbox">
                        <Checkbox
                          color="primary"
                          checked={isItemSelected}
                          inputProps={{
                            "aria-labelledby": labelId,
                          }}
                        />
                      </TableCell> */}
                        <TableCell
                          component="th"
                          id={labelId}
                          scope="row"
                          padding="none"
                        >
                          {index + 1}
                        </TableCell>
                        <TableCell align="left" width={200} sx={{}}>
                          {" "}
                          <Stack sx={{ ml: -1 }}>
                            <Typography align="left" variant="subtitle1">
                              {row.firstname}
                            </Typography>
                            <Typography
                              align="left"
                              variant="caption"
                              color="secondary"
                            >
                              {row.contactno}
                            </Typography>
                          </Stack>
                        </TableCell>
                        <TableCell align="left">{row.address}</TableCell>{" "}
                        <TableCell align="left">{row.suburb}</TableCell>
                        <TableCell align="center">
                          <Tooltip title={"To Edit"}>
                            <IconButton>
                              <RiEdit2Fill
                                fontSize={"large"}
                                style={{
                                  cursor: "pointer",
                                  color: theme.palette.primary.main,
                                }}
                                onClick={() => {
                                  setSelectedCustomer(row);
                                  handleClickOpen();
                                }}
                              />
                            </IconButton>
                          </Tooltip>
                        </TableCell>
                      </TableRow>
                    );
                  })
              )}
              {/* {emptyRows > 0 && (
                <TableRow sx={{ height: (dense ? 33 : 53) * emptyRows }}>
                  <TableCell colSpan={6} />
                </TableRow>
              )} */}
            </TableBody>
          </Table>
        </TableContainer>
        <Divider />
        {/* ======================================== || Edit Dialog || ======================================== */}
        <Dialog
          open={open}
          onClose={handleClose}
          aria-labelledby="alert-dialog-title"
          aria-describedby="alert-dialog-description"
          maxWidth="lg"
          fullWidth
        >
          <DialogTitle
            id="alert-dialog-title"
            sx={{ bgcolor: theme.palette.primary.main, color: "white" }}
          >
            <Stack direction={"row"} alignItems={"center"} spacing={1}>
              <FaRegEdit style={{ fontSize: 25 }} />{" "}
              <Typography variant="h3">Edit Customer</Typography>
            </Stack>
          </DialogTitle>
          <DialogContent>
            <Grid container spacing={2} sx={{ mt: 2 }}>
              <Grid item xs={6}>
                <Typography sx={{ mb: 1 }}>Customer Name</Typography>
                <TextField
                  variant="outlined"
                  fullWidth
                  defaultValue={selectedCustomer.firstname}
                  onChange={(e) => {
                    setSelectedCustomer({
                      ...selectedCustomer,
                      firstname: e.target.value,
                    });
                  }}
                />
              </Grid>

              <Grid item xs={6}>
                {" "}
                <Typography sx={{ mb: 1 }}>Contact Number</Typography>
                <Stack direction={"row"}>
                  <TextField
                    readonly
                    variant="outlined"
                    value={"+91"}
                    sx={{ width: 60 }}
                  />
                  <TextField
                    variant="outlined"
                    type="number"
                    fullWidth
                    defaultValue={selectedCustomer.contactno}
                    onChange={(e) => {
                      setSelectedCustomer({
                        ...selectedCustomer,
                        contactno: e.target.value,
                      });
                    }}
                  />
                </Stack>
              </Grid>

              <Grid item xs={12}>
                {" "}
                <Typography sx={{ mb: 1 }}>Address</Typography>
                <Autocomplete
                  id="google-map-demo"
                  sx={{}}
                  fullWidth
                  getOptionLabel={(option) =>
                    typeof option === "string" ? option : option.description
                  }
                  filterOptions={(x) => x}
                  options={options}
                  autoComplete
                  includeInputInList
                  filterSelectedOptions
                  value={selectedCustomer.address}
                  noOptionsText="No locations"
                  onChange={(event, newValue) => {
                    setOptions(newValue ? [newValue, ...options] : options);
                    setValue(newValue);
                    console.log("newValue", newValue.description);
                    setAddress(newValue.description);
                    setSelectedCustomer({
                      ...selectedCustomer,
                      address: newValue.description,
                    });
                  }}
                  onInputChange={(event, newInputValue) => {
                    setInputValue(newInputValue);
                  }}
                  renderInput={(params) => <TextField {...params} fullWidth />}
                  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 item xs={6}>
                {" "}
                <Typography sx={{ mb: 1 }}>Door No</Typography>
                <TextField
                  variant="outlined"
                  fullWidth
                  defaultValue={selectedCustomer.doorno}
                  onChange={(e) => {
                    setSelectedCustomer({
                      ...selectedCustomer,
                      doorno: e.target.value,
                    });
                  }}
                />
              </Grid>

              <Grid item xs={6}>
                <Typography sx={{ mb: 1 }}>Suburb</Typography>
                <TextField
                  variant="outlined"
                  fullWidth
                  value={selectedCustomer.suburb}
                  onChange={(e) => {
                    setSelectedCustomer({
                      ...selectedCustomer,
                      suburb: e.target.value,
                    });
                  }}
                />
              </Grid>

              <Grid item xs={6}>
                {" "}
                <Typography sx={{ mb: 1 }}>City</Typography>
                <TextField
                  variant="outlined"
                  fullWidth
                  value={selectedCustomer.city}
                  onChange={(e) => {
                    setSelectedCustomer({
                      ...selectedCustomer,
                      city: e.target.value,
                    });
                  }}
                />
              </Grid>

              <Grid item xs={6}>
                {" "}
                <Typography sx={{ mb: 1 }}>State</Typography>
                <TextField
                  variant="outlined"
                  fullWidth
                  value={selectedCustomer.state}
                  onChange={(e) => {
                    setSelectedCustomer({
                      ...selectedCustomer,
                      state: e.target.value,
                    });
                  }}
                />
              </Grid>

              <Grid item xs={6}>
                {" "}
                <Typography sx={{ mb: 1 }}>Postcode</Typography>
                <TextField
                  variant="outlined"
                  fullWidth
                  value={selectedCustomer.postcode}
                  onChange={(e) => {
                    setSelectedCustomer({
                      ...selectedCustomer,
                      postcode: e.target.value,
                    });
                  }}
                />
              </Grid>

              <Grid item xs={6}>
                {" "}
                <Typography sx={{ mb: 1 }}>Landmark</Typography>
                <TextField
                  variant="outlined"
                  fullWidth
                  defaultValue={selectedCustomer.landmark}
                  onChange={(e) => {
                    setSelectedCustomer({
                      ...selectedCustomer,
                      landmark: e.target.value,
                    });
                  }}
                />
              </Grid>

              <Grid item xs={6} sx={{ cursor: "not-allowed" }}>
                {" "}
                <Typography sx={{ mb: 1 }}>Latitude</Typography>
                <TextField
                  variant="outlined"
                  fullWidth
                  value={latlong.lat || selectedCustomer.latitude}
                  sx={{ cursor: "not-allowed" }}
                />
              </Grid>

              <Grid item xs={6} sx={{ cursor: "not-allowed" }}>
                {" "}
                <Typography sx={{ mb: 1 }}>Longitude</Typography>
                <TextField
                  readonly
                  variant="outlined"
                  fullWidth
                  value={latlong.lng || selectedCustomer.longitude}
                />
              </Grid>
            </Grid>
          </DialogContent>
          <DialogActions sx={{ mr: 2, mb: 2 }}>
            <Button
              onClick={handleClose}
              variant="contained"
              color="error"
              sx={{ mr: 2 }}
            >
              Close
            </Button>
            <Button
              onClick={() => {
                updateCustomer();
              }}
              variant="contained"
              autoFocus
            >
              Update
            </Button>
          </DialogActions>
        </Dialog>
        {/* table pagination */}
        {/* <TablePagination
          rowsPerPageOptions={[5, 10, 25]}
          component="div"
          count={rows.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        /> */}{" "}
        <Grid container>
          <Grid item xs={12}>
            <Stack
              direction={"row"}
              justifyContent={"flex-end"}
              alignItems={"center"}
              spacing={2}
              style={{ height: "60px", margin: "0px 10px" }}
            >
              <IconButton
                style={{
                  padding: "0px",
                  color: pages > 1 ? "#65387A" : "grey",
                  backgroundColor: "#f3e5f5",
                }}
                onClick={() => {
                  if (pages > 1) {
                    setPages((prevValue) => prevValue - 1);
                    // fetchCustomersList(pages - 1);
                  }
                }}
              >
                <LeftOutlined style={{ fontSize: "12px" }} />
              </IconButton>

              <Typography variant="h6">{pages}</Typography>

              <IconButton
                style={{
                  color: "#65378A",
                  padding: "0px",
                  backgroundColor: "#f3e5f5",
                }}
                onClick={() => {
                  setPages((prevValue) => prevValue + 1);
                }}
              >
                <RightOutlined style={{ fontSize: "12px" }} />
              </IconButton>
            </Stack>
          </Grid>
        </Grid>
      </MainCard>
    </>
  );
}
