import React from 'react';
import { Avatar, Pagination, Tooltip, stepContentClasses } from '@mui/material';
import { useEffect, useRef, useState, Fragment, useMemo } from 'react';
import { useTheme } from '@mui/material/styles';
import Skeleton from '@mui/material/Skeleton';
import HeartFilled from '@mui/icons-material/Favorite';
// import dayjs from "dayjs";
import Loader from 'components/Loader';
import CloseIcon from '@mui/icons-material/Close';
import { FilterList } from '@mui/icons-material';
import { FaRegEdit } from 'react-icons/fa';
import { RiEdit2Fill } from 'react-icons/ri';
import { enqueueSnackbar } from 'notistack';

import {
  Box,
  Button,
  IconButton,
  ClickAwayListener,
  Collapse,
  Dialog,
  Grid,
  Menu,
  MenuItem,
  Popper,
  Stack,
  TextField,
  Typography,
  useMediaQuery,
  Chip,
  OutlinedInput,
  InputAdornment,
  List,
  Divider,
  ListItemButton,
  ListItemAvatar,
  ListItemText,
  DialogTitle,
  DialogContent,
  DialogActions,
  InputLabel,
  Table,
  TableContainer,
  TableHead,
  TableCell,
  TableBody,
  TableRow,
  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 ClearIcon from '@mui/icons-material/Clear';
import { MdPersonAdd } from 'react-icons/md';
// import { MdAccountCircle } from "react-icons/md";
import { MdPersonAddDisabled } from 'react-icons/md';
// import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
// import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
// import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { ThemeMode } from 'config';
// import { FaUserLarge } from "react-icons/fa6";
import { MoreOutlined, SearchOutlined, DeleteFilled } from '@ant-design/icons';
// import ChatDrawer from "sections/apps/chat/ChatDrawer";
// import ChatHistory from "sections/apps/chat/ChatHistory";
// import UserAvatar from "sections/apps/chat/UserAvatar";
// import UserDetails from "sections/apps/chat/UserDetails";
import MainCard from 'components/MainCard';
// import IconButton from "components/@extended/IconButton";
// import SimpleBar from "components/third-party/SimpleBar";
import { PopupTransition } from 'components/@extended/Transitions';
import axios from 'axios';
// import HoverSocialCard from "../../pages/reports/HoverSocialCard";
import HoverSocialCard from 'components/cards/statistics/HoverSocialCard';
// import TasksCard from "sections/widget/data/TasksCard";
// import ApplicationSales from "sections/widget/data/ApplicationSales";
// import Button from "themes/overrides/Button";
import { styled } from '@mui/material/styles';
// import TableRow from "themes/overrides/TableRow";
import dayjs from 'dayjs';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
import { DateRangePicker } from 'mui-daterange-picker';

import {
  addDays,
  addMonths,
  addWeeks,
  // addYears,
  endOfMonth,
  endOfWeek,
  // endOfYear,
  startOfMonth,
  startOfWeek
  // startOfYear,
} from 'date-fns';
const drawerWidth = 320;
// const Main = styled("main", { shouldForwardProp: (prop) => prop !== "open" })(
//   ({ theme, open }) => ({
//     flexGrow: 1,
//     transition: theme.transitions.create("margin", {
//       easing: theme.transitions.easing.sharp,
//       duration: theme.transitions.duration.shorter,
//     }),
//     marginLeft: `-${drawerWidth}px`,
//     [theme.breakpoints.down("lg")]: {
//       paddingLeft: 0,
//       marginLeft: 0,
//     },
//     ...(open && {
//       transition: theme.transitions.create("margin", {
//         easing: theme.transitions.easing.easeOut,
//         duration: theme.transitions.duration.shorter,
//       }),
//       marginLeft: 0,
//     }),
//   })
// );

// ==============================|| 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 };

const BootstrapDialog = styled(Dialog)(({ theme }) => ({
  '& .MuiDialog-paperWidthSm': {
    maxWidth: '60%',
    width: '100%',
    margin: 0
  },
  '& .MuiDialogContent-root': {
    padding: theme.spacing(2)
  },
  '& .MuiDialogActions-root': {
    padding: theme.spacing(1)
  }
}));

const Customers = () => {
  const theme = useTheme();
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [users, setUsers] = useState([]);
  const [userName, setUserName] = useState('');
  const [usernameload, setUsernameload] = useState(false);
  const [customerId, setCustomerId] = useState('');
  const [custVisits, setCustVisits] = useState([]);
  const [custService, setCustService] = useState([]);
  const [custMembership, setCustMembership] = useState({});
  const [visits, setvisits] = useState(0);
  const [billAmount, setBillAmount] = useState(0);
  const [promotions, setPromotions] = useState(0);
  const [discount, setDiscount] = useState(0);
  const [pageno, setPageno] = useState(1);
  const [contactno, setContactno] = useState('');
  const ref = useRef(null);
  const [open, setOpen] = React.useState(false);
  const [open3, setOpen3] = React.useState(false);
  const [open4, setOpen4] = React.useState(false);
  const [selectedCustomer, setSelectedCustomer] = useState({}); // to edit

  const [packDays, setPackDays] = useState(0);
  const [startDate, setStartDate] = useState('');
  const [validDate, setValidDate] = useState('');
  const [orderlist, setOrderlist] = useState([]);
  const [allorders, setAllorders] = useState('');
  const [coveredorders, setCoveredorders] = useState('');
  const [uncoveredorders, setUncoveredorders] = useState('');
  const [cancelled, setCancelled] = useState('');

  const [percentage1, setPercentage1] = useState('0');
  const [percentage2, setPercentage2] = useState('0');
  const [percentage3, setPercentage3] = useState('0');
  const [percentage4, setPercentage4] = useState('0');

  const [tempusers, setTempusers] = useState([]);

  const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
  const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));

  const [datestatus, setDatestatus] = useState('Today');
  const [tenid, setTenid] = useState('');
  const [loading1, setLoading1] = useState(false);
  const [currentcustomerid, setCurrentcustomerid] = useState('');

  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
            });
          }
        },
        (error) => {
          console.log(error);
        }
      );
    } catch (err) {
      console.log(err);
    }
  }, [address]);

  useEffect(() => {
    selectedCustomer &&
      setLatlong({
        lat: selectedCustomer.latitude,
        lng: selectedCustomer.longitude
      });
  }, [selectedCustomer]);

  const openToast = (message, variant, duration) => {
    enqueueSnackbar(message, {
      variant: variant,
      anchorOrigin: { vertical: 'top', horizontal: 'right' },
      autoHideDuration: duration
    });
  };

  useEffect(() => {
    console.log('selectedCustomer', selectedCustomer);
  }, [selectedCustomer]);

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

  const handleClickOpen4 = () => {
    setOpen4(true);
  };

  const handleClose4 = () => {
    setOpen4(false);
  };
  /* ============================================= || handleKeyPress (ctrl+k)| ============================================= */
  const textFieldRef = useRef(null);

  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);
    };
  }, []);
  const handleClickOpen = () => {
    setOpen(true);
  };
  const handleClose = () => {
    setOpen3(false);
  };

  const handleClose3 = () => {
    setOpen3(false);
  };
  // const [anchorEl]=useState(null)
  // const tenid = window.localStorage.getItem("tenantid");
  useEffect(() => {
    // setUsernameload(false);
    console.log('username', userName);
  }, [userName]);

  const [anchorEl, setAnchorEl] = useState();
  const handleClickRightMenu = (event) => {
    setAnchorEl(event?.currentTarget);
  };

  const handleCloseRightMenu = () => {
    setAnchorEl(null);
  };
  const handleClickSort = (event) => {
    setAnchorEl(event?.currentTarget);
  };

  const handleCloseSort = () => {
    setAnchorEl(null);
  };

  useEffect(() => {
    if (localStorage.getItem('tenantid')) {
      fetchtable(localStorage.getItem('tenantid'));
    }
  }, []);

  useEffect(() => {
    if (tenid && !search) {
      //   fetchData1();
    }
  }, [pageno]);

  useEffect(() => {
    const fetchsearch = async () => {
      setLoading(true);
      try {
        await axios
          .get(`${process.env.REACT_APP_URL}/customers/search?tenantid=${tenid}&keyword=${search}`)
          .then((response) => {
            if (response.data.status) {
              setUsers(response.data.details || []);
              setLoading(false);
            }
          })
          .catch((err) => {
            console.log(err);
            setLoading(false);
          });
      } catch (error) {
        console.error('Error fetching data:', error);
        setLoading(false);
      }
    };
    if (search.length > 2) {
      // fetchsearch();
    } else if (!search) {
      //   fetchData1();
      setPageno(1);
    }
  }, [search]);

  useEffect(() => {
    if (search) {
      let arr = tempusers.filter((val) => {
        return (
          val.firstname.toLowerCase().includes(search.toLowerCase()) ||
          // || val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
          // || val.customername.toLowerCase().includes(searchword.toLowerCase())
          // || val.pickupaddress.toString().toLowerCase().includes(searchword.toLowerCase())
          // || val.ordernotes.toString().toLowerCase().includes(searchword.toLowerCase())
          val.contactno.toString().toLowerCase().includes(search.toLowerCase())
        );
      });
      console.log(arr);
      setUsers([...arr]);
    } else {
      setUsers([...tempusers]);
    }
  }, [search]);

  useEffect(() => {
    if (tenid) {
      fetchData(tenid);
    }
  }, [startdate, enddate]);

  const fetchpercentage = async (tid) => {
    setLoading(true);
    try {
      // await axios.get(`${process.env.REACT_APP_URL}/orders/getordersummary/?tenantid=${tid}&fromdate=${startdate}&todate=${enddate}`)
      await axios
        .get(`${process.env.REACT_APP_URL}/orders/getordersummary/?customerid=${tid}`)

        .then((res) => {
          console.log(res);
          // setConfirmed(res.data.details.confirmed.toString());
          // setModified(res.data.details.modified.toString());
          setAllorders(res.data.details.total.toString());
          setCoveredorders(res.data.details.delivered.toString());

          setCancelled(res.data.details.cancelled.toString());
          setUncoveredorders(res.data.details.pending.toString());
          // setActiveorders(res.data.details.assigned.toString());
          // setAssigned(res.data.details.accepted.toString());
          // setCreated(res.data.details.created.toString())
          // setClosed(res.data.details.delivered.toString());
          // setPicked(res.data.details.picked.toString())
          setPercentage1((Math.round((res.data.details.total / res.data.details.total) * 100) || 0).toString());
          setPercentage3((Math.round((res.data.details.delivered / res.data.details.total) * 100) || 0).toString());

          setPercentage4((Math.round((res.data.details.cancelled / res.data.details.total) * 100) || 0).toString());

          setPercentage2((Math.round((res.data.details.pending / res.data.details.total) * 100) || 0).toString());

          setLoading(false);
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
          //   enqueueSnackbar(err.message, {
          //     variant: 'error', anchorOrigin: { vertical: 'top', horizontal: 'right' },
          //     autoHideDuration: 2000
          // })
        });
    } catch (err) {
      console.log(err);
      setLoading(false);
    }
  };

  const removeclient = async () => {
    setLoading(true);
    try {
      await axios
        .delete(`${process.env.REACT_APP_URL}/customers/delete/?customerid=${currentcustomerid}`)

        .then((res) => {
          if (res.data.status) {
            enqueueSnackbar('Deleted Successfully', {
              variant: 'success',
              anchorOrigin: { vertical: 'top', horizontal: 'right' },
              autoHideDuration: 2000
            });
            setCurrentcustomerid('');
            // fetchtable(localStorage.getItem('tenantid'))
          } else {
            enqueueSnackbar(res.data.message, {
              variant: 'error',
              anchorOrigin: { vertical: 'top', horizontal: 'right' },
              autoHideDuration: 2000
            });
          }
          setLoading(false);
        })
        .catch((err) => {
          console.log(err);
          enqueueSnackbar(err.message, {
            variant: 'error',
            anchorOrigin: { vertical: 'top', horizontal: 'right' },
            autoHideDuration: 2000
          });
          setLoading(false);
        });
    } catch (err) {
      console.log(err);
      setLoading(false);
    }
  };

  const fetchtable = async (tid) => {
    setLoading1(true);
    try {
      // await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenants/?partnerid=${tid}&status=active`)
      await axios
        // .get(`${process.env.REACT_APP_URL}/customers/gettenantcustomers/?tenantid=${tid}`)
        .get(`${process.env.REACT_APP_URL}/customers/gettenantcustomers/?tenantid=${tid}&pageno=1&pagesize=20`)

        .then((res) => {
          if (res.data.message === 'Success') {
            let arr = [];
            res.data.details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            // setArr(arr)
            // setRows([...arr])
            // setStafflist([...arr])
            setSelectedCustomer(arr[0]);
            setUsers([...arr]);
            setTempusers([...arr]);
            // if(arr[0].customerid){
            setTenid(arr[0].customerid);
            setUserName(arr[0].firstname || '');
            setContactno(arr[0].contactno || '');
            fetchpercentage(arr[0].customerid);
            fetchData(arr[0].customerid);
            // }

            console.log(res.data.Details);
            console.log(arr);
            setLoading1(false);
          }
        })
        .catch((err) => {
          console.log(err);
          setLoading1(false);
          enqueueSnackbar(err.message, {
            variant: 'error',
            anchorOrigin: { vertical: 'top', horizontal: 'right' },
            autoHideDuration: 2000
          });
        });
    } catch (err) {
      console.log(err);
      setLoading1(false);
    }
  };

  const fetchData1 = async () => {
    setLoading(true);
    try {
      await axios
        .get(`${process.env.REACT_APP_URL}/customers/getbytid?tenantid=${tenid}&pageno=${pageno}&pagesize=20`)
        .then((response) => {
          if (response.data.status) {
            setUsers(
              response.data.details
              // .slice(0, 10)
            );
            setUserName(response.data.details[0].firstname || '');
            setContactno(response.data.details[0].contactno || '');
            fetchData(response.data.details[0].customerid);

            // fetchData(user.customerid);
          }
          setLoading(false);
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
        });
    } catch (error) {
      console.error('Error fetching data:', error);
      setLoading(false);
    }
  };

  const fetchData = async (tid) => {
    try {
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/customer/getorders/?customerid=${tid}&status=delivered&fromdate=${startdate}&todate=${enddate}`
        )
        .then((res) => {
          if (res.data.message === 'Success') {
            let arr = [];
            res.data.details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            // setArruncovered(arr)
            setOrderlist([...arr]);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(() => {
    console.log('packDays', packDays);
    console.log('startDate', startDate);
    const formattedDate = dayjs(startDate, 'DD/MM/YYYY').add(packDays, 'day').format('DD/MM/YYYY');
    setValidDate(formattedDate);
  }, [packDays, startDate]);

  function AlertCustomerDelete({
    // title,
    open,
    handleClose
  }) {
    // const [deletepassword, setDeletepassword] = useState('');

    return (
      <Dialog open={open} onClose={() => handleClose(false)} maxWidth="xs">
        <DialogContent sx={{ mt: 2, my: 1 }}>
          <Stack alignItems="center" spacing={3.5}>
            <Avatar color="error" sx={{ width: 72, height: 72, fontSize: '1.75rem' }}>
              <DeleteFilled />
            </Avatar>
            {/* <Grid >
              <Chip label={orderid.slice(4)} variant="combined" color='warning' size='small' />
            </Grid> */}
            <Stack spacing={2}>
              <Typography variant="h4" align="center">
                Are you sure you want to Remove this Customer?
              </Typography>

              {/* <Typography variant="h4" align="center">
                Please type in the order number to confirm.
              </Typography> */}
              {/* <TextField
                type='text'
                onChange={(e) => {
                  console.log(e.target.value)
                  setDeletepassword(e.target.value)
                }}
                error={deletepassword !== orderid.slice(4)}
                value={deletepassword}
              /> */}
            </Stack>

            <Stack direction="row" spacing={2} sx={{ width: 1 }}>
              <Button
                fullWidth
                color="error"
                variant="contained"
                onClick={() => {
                  // if (deletepassword === orderid.slice(4)) {
                  //   cancelorder();
                  removeclient();
                  handleClose(true);
                  // }
                }}
                autoFocus
              >
                Yes, Remove
              </Button>
              <Button
                fullWidth
                onClick={() => {
                  handleClose(false);
                  setCurrentcustomerid('');
                }}
                color="secondary"
                variant="outlined"
              >
                No
              </Button>
            </Stack>
          </Stack>
        </DialogContent>
      </Dialog>
    );
  }

  // ==============================|| 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);
          handleClose4();
          fetchtable(localStorage.getItem('tenantid'));
        }
      } catch (error) {
        console.log('postUpdate error', error);
      }
    }
  };

  return (
    <>
      {(loading || usernameload) && <Loader />}
      <AlertCustomerDelete open={open3} handleClose={handleClose} />

      <Grid container rowSpacing={2} columnSpacing={2.75}>
        <Grid item xs={12}>
          <Stack direction="row" justifyContent="space-between" alignItems="center">
            <Typography variant="h3">Customers</Typography>
          </Stack>
        </Grid>
        <Grid item xs={12}>
          <Box
            sx={{
              display: 'flex',
              width: '100%',
              // height: "580px",
              // bgcolor: "red",
              height: '100%'
            }}
          >
            <MainCard
              sx={{
                // bgcolor: matchDownLG ? "transparent" : drawerBG,
                borderRadius: '4px 0 0 4px',
                borderRight: 'none',
                width: 320,
                // width:'100%',
                height: '100%'
                // height: "580px"
                // height: "100%",
                // overflowY: "scroll",
                // scrollbarWidth: "thin", // Hide scrollbar in Firefox
                // "&::-webkit-scrollbar": {
                //   width: "5px", // Customize the width of the scrollbar
                // },
                // "&::-webkit-scrollbar-thumb": {
                //   backgroundColor: "#ce93d8", // Customize the scrollbar thumb color
                //   borderRadius: "6px", // Round the scrollbar thumb
                // },
              }}
              // border={!matchDownLG}
              content={false}
            >
              <Box sx={{ p: 3, pb: 1 }}>
                <Stack spacing={2}>
                  {/* <Stack direction="row" spacing={0.5} alignItems="center">
              <Typography variant="h5" color="inherit">
                Customers
              </Typography>
              <Chip
                label="9"
                component="span"
                color="secondary"
                sx={{
                  width: 20,
                  height: 20,
                  borderRadius: "50%",
                  "& .MuiChip-label": {
                    px: 0.5,
                  },
                }}
              />
            </Stack> */}

                  <OutlinedInput
                    inputRef={textFieldRef}
                    fullWidth
                    id="input-search-header"
                    placeholder="Search (ctrl+k)"
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    // onChange={handleSearch}
                    sx={{
                      '& .MuiOutlinedInput-input': {
                        p: '10.5px 0px 12px'
                      }
                    }}
                    startAdornment={
                      <InputAdornment position="start">
                        <SearchOutlined style={{ fontSize: 'small' }} />
                      </InputAdornment>
                    }
                    endAdornment={
                      <Tooltip title="clear">
                        <IconButton
                          sx={{ visibility: search ? 'visible' : 'hidden' }}
                          onClick={() => {
                            setSearch('');
                          }}
                        >
                          <ClearIcon />
                        </IconButton>
                      </Tooltip>
                    }
                  />
                </Stack>
              </Box>

              {/* <SimpleBar
          sx={{
            overflowX: "hidden",

          }}
        > */}
              <Box
                sx={{
                  // height: "450px",
                  height: '600px',

                  // height: "1515px",
                  // height: "100%",
                  overflowY: 'scroll',
                  scrollbarWidth: 'thin', // Hide scrollbar in Firefox
                  '&::-webkit-scrollbar': {
                    width: '3px' // Customize the width of the scrollbar
                  },
                  '&::-webkit-scrollbar-thumb': {
                    backgroundColor: '#65387A', // Customize the scrollbar thumb color
                    borderRadius: '6px' // Round the scrollbar thumb
                  },
                  p: 3,
                  pt: 0
                }}
              >
                {/* <UserList setUser={setUser} search={search} /> */}
                {loading1 ? (
                  <>
                    {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((val1) => {
                      return (
                        <>
                          <Stack direction={'row'}>
                            <Skeleton variant="circular" width={40} height={40} />
                            <Stack direction={'column'} sx={{ width: '80%' }}>
                              <Skeleton variant="text" sx={{ fontSize: '1rem' }} />
                              <Skeleton variant="text" sx={{ fontSize: '1rem' }} />
                            </Stack>
                          </Stack>
                        </>
                      );
                    })}

                    {/* <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="circular" width={40} height={40} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} />
              <Skeleton variant="text" sx={{ fontSize: "1rem" }} /> */}
                  </>
                ) : (
                  <List component="nav">
                    {users.map((user, index) => (
                      <Fragment key={user.sno}>
                        <ListItemButton
                          sx={{ pl: 1 }}
                          onClick={() => {
                            setTenid(user.customerid);
                            setUserName(user.firstname);
                            setContactno(user.contactno);
                            fetchData(user.customerid);
                            fetchpercentage(user.customerid);
                            setSelectedCustomer(user);
                          }}
                        >
                          <ListItemAvatar>
                            <Avatar
                              // user={user}
                              style={{ background: '#65387A' }}
                            />
                          </ListItemAvatar>
                          <ListItemText
                            primary={
                              <Stack component="span" direction="row" alignItems="center" justifyContent="space-between" spacing={1}>
                                <Typography
                                  variant="h6"
                                  color="inherit"
                                  sx={{
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                    whiteSpace: 'nowrap'
                                  }}
                                >
                                  {user.firstname}
                                </Typography>
                                <Typography component="span" color="textSecondary" variant="caption">
                                  {/* {user.lastMessage} */}
                                </Typography>
                              </Stack>
                            }
                            secondary={
                              <Stack component="span" direction="row" alignItems="center" justifyContent="space-between" spacing={1}>
                                <Typography
                                  variant="caption"
                                  color="textSecondary"
                                  sx={{
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                    whiteSpace: 'nowrap'
                                  }}
                                >
                                  {user.contactno}
                                </Typography>
                                {/* {user.unReadChatCount ? (
                    <Dot color="primary" />
                  ) : (
                    // chance.bool() - use for last send msg was read or unread
                    <CheckOutlined
                      style={{
                        color: chance.bool()
                          ? theme.palette.grey[400]
                          : theme.palette.primary.main,
                      }}
                    />
                  )} */}
                              </Stack>
                            }
                          />
                        </ListItemButton>
                        <Divider />
                      </Fragment>
                    ))}
                  </List>
                )}
              </Box>
              {/* <Box
                sx={{ width: "100%", p: 2 }}
              >
                <Grid container>
                  <Grid item xs={12}>

                    <Stack
                      direction={"row"}
                      justifyContent={"flex-end"}
                      alignItems={"center"}
                      spacing={1}
                    >
                      <IconButton
                        color="primary"
                        size="small"
                        onClick={() => {
                          let val = pageno;
                          if (val > 1) {
                            val = val - 1;
                            setPageno(val);
                          }
                        }}
                      >
                        <LeftOutlined />
                      </IconButton>
                      <Typography variant="h6">{pageno}</Typography>
                      <IconButton
                        color="primary"
                        size="small"
                        onClick={() => {
                          let val = pageno;
                          if (val > 0 && !search) {
                            val = val + 1;
                            setPageno(val);
                          }
                        }}
                      >
                        <RightOutlined />
                      </IconButton>
                    </Stack>
                  </Grid>
                </Grid>
              </Box> */}
              {/* </SimpleBar> */}
              <Box sx={{ width: '100%', p: 2 }}>
                <Stack direction={'row'} justifyContent={'flex-end'}>
                  <Typography variant="h6">{users.length} Customers</Typography>
                </Stack>
              </Box>
            </MainCard>

            {/* <ChatDrawer
      openChatDrawer={openChatDrawer}
      handleDrawerOpen={handleDrawerOpen}
      setUser={setUser}
      /> */}
            {/* <Main
        theme={theme} open={openChatDrawer}
      > */}

            <Grid
              container
              sx={{
                width: 'calc(100% - 320px)',
                height: '100%'
              }}
              style={{
                // height: "580px",
                // height: '100%',
                background: ''
                // borderBottom: "1px solid #eeeeee",
              }}
            >
              <Grid
                item
                xs={12}
                //   md={emailDetails ? 8 : 12}
                //   xl={emailDetails ? 9 : 12}
                sx={{
                  transition: theme.transitions.create('width', {
                    easing: theme.transitions.easing.easeOut,
                    duration: theme.transitions.duration.shorter + 200
                    // height: "100%",
                  })
                }}
              >
                <MainCard
                  content={false}
                  sx={{
                    height: '100%',
                    // marginBottom:'60px' ,

                    bgcolor: theme.palette.mode === ThemeMode.DARK ? 'dark.main' : 'grey.50',
                    // pt: 2,
                    // pl: 2,
                    // borderRadius: emailDetails ? "0" : "0 4px 4px 0",
                    transition: theme.transitions.create('width', {
                      easing: theme.transitions.easing.easeOut,
                      duration: theme.transitions.duration.shorter + 200
                    })
                  }}
                >
                  <Grid container spacing={3} sx={{ height: '100%' }}>
                    <Grid
                      item
                      xs={12}
                      sx={{
                        bgcolor: theme.palette.background.paper,
                        pr: 2,
                        pb: 2,
                        borderBottom: `1px solid ${theme.palette.divider}`
                        // height:'100%'
                      }}
                    >
                      <Grid container justifyContent="space-between">
                        <Grid item sx={{ ml: 2, mt: 2 }}>
                          <Stack direction="row" alignItems="center" spacing={2}>
                            <Avatar
                              // user={user}
                              style={{ background: '#65387A' }}
                            />

                            {userName ? (
                              <Stack direction={'column'}>
                                <Typography variant="subtitle1">{userName}</Typography>
                                <Typography variant="subtitle1" color={'secondary'}>
                                  {contactno}
                                </Typography>
                              </Stack>
                            ) : (
                              <Stack direction={'column'}>
                                <Skeleton variant="text" sx={{ fontSize: '1rem', width: '75px' }} />
                                <Skeleton variant="text" sx={{ fontSize: '1rem', width: '75px' }} />
                              </Stack>
                            )}
                          </Stack>
                        </Grid>
                        <Grid item sx={{ ml: 2, mt: 2 }}>
                          <Stack direction="row" alignItems="center" spacing={2} sx={{ height: '100%' }}>
                            {custMembership.membershipid == 0 && custMembership.startdate == '' ? (
                              <>{/* <h4>No Membership Found</h4> */}</>
                            ) : (
                              <>
                                {custMembership.membershipid && (
                                  <>
                                    <Tooltip title="Membership No" sx={{ cursor: 'pointer' }}>
                                      <Chip
                                        icon={
                                          <HeartFilled
                                            style={{
                                              color: custMembership.string == 'expired' ? 'grey' : 'red'
                                            }}
                                          />
                                        }
                                        variant="caption"
                                        label={custMembership.membershipno || ''}
                                        style={{
                                          width: 'auto',
                                          height: 'auto',

                                          color: 'black',
                                          background: 'white'
                                        }}
                                      />
                                    </Tooltip>
                                    <Tooltip title="Start Date" sx={{ cursor: 'pointer' }}>
                                      <Chip
                                        color={custMembership.string == 'expired' ? 'secondary' : 'success'}
                                        label={dayjs(custMembership.startdate).format('DD-MM-YYYY') || ''}
                                        style={{
                                          width: 'auto',
                                          height: 'auto'
                                        }}
                                      />
                                    </Tooltip>
                                    <Tooltip title="End Date" sx={{ cursor: 'pointer' }}>
                                      <Chip
                                        color={custMembership.string == 'expired' ? 'secondary' : 'error'}
                                        label={dayjs(custMembership.enddate).format('DD-MM-YYYY') || ''}
                                        style={{
                                          width: 'auto',
                                          height: 'auto'
                                        }}
                                      />
                                    </Tooltip>
                                    {/* <Typography align="left" variant="body2">
                                {/* {custMembership.validityperiod || ''} Days */}
                                    {/* {` ${custMembership.string}` || ''}
                              </Typography> */}
                                    <Chip
                                      label={custMembership.string}
                                      color="error"
                                      style={{
                                        width: 'auto',
                                        height: 'auto'
                                      }}
                                    />
                                  </>
                                )}{' '}
                              </>
                            )}
                            <IconButton onClick={handleClickSort} size="large" color="primary">
                              <MoreOutlined />
                            </IconButton>

                            <Menu
                              id="simple-menu"
                              anchorEl={anchorEl}
                              keepMounted
                              open={Boolean(anchorEl)}
                              onClose={handleCloseSort}
                              anchorOrigin={{
                                vertical: 'bottom',
                                horizontal: 'right'
                              }}
                              transformOrigin={{
                                vertical: 'top',
                                horizontal: 'right'
                              }}
                              sx={{
                                p: 0,
                                '& .MuiMenu-list': {
                                  p: 0
                                }
                              }}
                            >
                              <MenuItem onClick={handleCloseSort}>
                                <Button
                                  variant="text"
                                  onClick={() => {
                                    setOpen3(true);
                                    setCurrentcustomerid(tenid);
                                  }}
                                >
                                  {
                                    <DeleteFilled
                                      style={{
                                        fontSize: '12px',
                                        marginRight: '15px'
                                      }}
                                    />
                                  }{' '}
                                  Delete
                                </Button>
                                {/* ======================================== || Add Membership dialog|| ======================================== */}

                                {/* <BootstrapDialog
                                  onClose={handleClose}
                                  aria-labelledby="customized-dialog-title"
                                  open={open}
                                >
                                  <DialogTitle
                                    sx={{
                                      m: 0,
                                      p: 2,
                                      display: "flex",
                                      justifyContent: "space-between",
                                      color: "white",
                                      bgcolor: "#65378A",
                                    }}
                                    id="customized-dialog-title"
                                  >
                                    {" "}
                                    <div style={{ display: "flex" }}>
                                      <MdAccountCircle
                                        style={{
                                          fontSize: "40px",
                                          marginLeft: "10px",
                                          marginRight: "15px",
                                        }}
                                      />

                                      <Typography variant="h4" sx={{ mt: 1 }}>
                                        {" "}
                                        {`${userName} (${contactno})`}
                                      </Typography>
                                    </div>
                                  </DialogTitle>


                                  <DialogContent dividers>
                                    <Grid container spacing={3} sx={{ p: 1 }}>
                                      <Grid item xs={6}>
                                        <InputLabel sx={{ mb: 1 }}>
                                          Membership Number
                                        </InputLabel>
                                        <TextField
                                          fullWidth
                                          id="outlined-read-only-input"
                                          defaultValue={
                                            custMembership.membershipno
                                          }
                                          InputProps={{
                                            readOnly: true,
                                          }}
                                        />
                                      </Grid>
                                      <Grid item xs={6}>
                                        <InputLabel sx={{ mb: 1 }}>
                                          Select Package
                                        </InputLabel>
                                        <TextField
                                          id="outlined-select-currency"
                                          fullWidth
                                          select
                                          onChange={(e) => {
                                            setPackDays(e.target.value);
                                            console.log(e.target.value);

                                          }}
                                        >
                                          <MenuItem value="30">
                                            Trendy (30 days)
                                          </MenuItem>
                                          <MenuItem key="100" value="60">
                                            {" "}
                                            Premiun (60 days)
                                          </MenuItem>
                                          <MenuItem key="100" value="90">
                                            {" "}
                                            Gold (90 days)
                                          </MenuItem>
                                          <MenuItem key="100" value="365">
                                            {" "}
                                            Platinum (365 days)
                                          </MenuItem>
                                        </TextField>
                                      </Grid>
                                      <Grid item xs={6} sx={{}}>
                                        <InputLabel sx={{ mb: 1 }}>
                                          Start Date
                                        </InputLabel>
                                        <LocalizationProvider
                                          dateAdapter={AdapterDayjs}
                                        >
                                          <DatePicker
                                            sx={{ width: "100%" }}
                                            format="DD/MM/YYYY"
                                            disablePast
                                            renderInput={(params) => (
                                              <TextField {...params} />
                                            )}
                                            onChange={(e) => {
                                              setStartDate(
                                                e.format("DD/MM/YYYY")
                                              );
                                              console.log(
                                                e.format("DD/MM/YYYY")
                                              );
                                            }}
                                          />
                                        </LocalizationProvider>
                                      </Grid>
                                      <Grid item xs={6} sx={{}}>
                                        <InputLabel sx={{ mb: 1 }}>
                                          Validity
                                        </InputLabel>
                                        <LocalizationProvider
                                          dateAdapter={AdapterDayjs}
                                        >
                                          <DatePicker
                                            sx={{ width: "100%" }}
                                            readOnly
                                            disablePast
                                            label={
                                              validDate == "Invalid Date"
                                                ? "End date"
                                                : validDate
                                            }
                                            renderInput={(params) => (
                                              <TextField {...params} />
                                            )}
                                          />
                                        </LocalizationProvider>
                                      </Grid>
                                    </Grid>
                                  </DialogContent>
                                  <DialogActions>
                                    <Button
                                      autoFocus
                                      variant="outlined"
                                      onClick={() => {
                                        handleClose();
                                        setPackDays(0);
                                        setStartDate();
                                        setValidDate();
                                      }}
                                      sx={{
                                        "&:hover": {
                                          backgroundColor: "#65378A",
                                          color: "white",
                                        },
                                        m: 2,
                                        mr: 5,
                                        px: 3,
                                      }}
                                    >
                                      Cancel
                                    </Button>
                                    <Button
                                      autoFocus
                                      variant="contained"
                                      sx={{
                                        "&:hover": {

                                        },
                                        mr: 1.5,
                                        px: 5,
                                      }}
                                      onClick={handleClose}
                                    >
                                      Add
                                    </Button>
                                  </DialogActions>
                                </BootstrapDialog> */}
                              </MenuItem>
                              <MenuItem onClick={handleCloseSort}>
                                <Button
                                  variant="text"
                                  onClick={() => {
                                    handleClickOpen4();
                                  }}
                                >
                                  {
                                    <RiEdit2Fill
                                      style={{
                                        fontSize: '12px',
                                        marginRight: '15px'
                                      }}
                                    />
                                  }{' '}
                                  Edit
                                </Button>
                              </MenuItem>
                              {/*  <MenuItem onClick={handleCloseSort}>
                                <Button
                                  variant="text"
                                  // onClick={handleClickOpen}
                                >
                                  {
                                    <MdPersonAddDisabled
                                      style={{
                                        fontSize: "20px",
                                        marginRight: "15px",
                                      }}
                                    />
                                  }{" "}
                                  Disable
                                </Button>
                              </MenuItem>*/}
                              {/* <MenuItem onClick={handleCloseSort}>
                            <DeleteOutlined style={{ paddingRight: 8 }} />
                            <Typography>Delete</Typography>
                          </MenuItem> */}
                            </Menu>
                          </Stack>
                        </Grid>
                      </Grid>
                    </Grid>
                    {/* ======================================== || Edit Dialog || ======================================== */}
                    <Dialog
                      open={open4}
                      onClose={handleClose4}
                      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"
                                fullWidth
                                defaultValue={selectedCustomer.contactno}
                                onChange={(e) => {
                                  setSelectedCustomer({
                                    ...selectedCustomer,
                                    contactno: e.target.value
                                  });
                                }}
                                inputProps={{
                                  maxLength: 10
                                }}
                              />
                            </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
                              defaultValue={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
                              defaultValue={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
                              defaultValue={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
                              defaultValue={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} 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} />
                          </Grid>
                        </Grid>
                      </DialogContent>
                      <DialogActions sx={{ mr: 2, mb: 2 }}>
                        <Button onClick={handleClose4} variant="contained" color="error" sx={{ mr: 2 }}>
                          Close
                        </Button>
                        <Button
                          onClick={() => {
                            updateCustomer();
                          }}
                          variant="contained"
                          autoFocus
                        >
                          Update
                        </Button>
                      </DialogActions>
                    </Dialog>
                    {/* ======================================== || Cards || ======================================== */}
                    <Grid
                      item
                      xs={12}
                      sx={{
                        //  "&::-webkit-scrollbar": {
                        //   width: "3px", // Customize the width of the scrollbar
                        // },
                        // "&::-webkit-scrollbar-thumb": {
                        //   backgroundColor: "#65387A", // Customize the scrollbar thumb color
                        // },
                        height: '100%'
                        // height: '415px',
                        // overflowY:'scroll',
                      }}
                    >
                      {/* <SimpleBar
                  sx={{
                    // overflowX: "hidden",


                    // height: "calc(100vh - 410px)",
                    // minHeight: 200,
                  }}
                > */}
                      <Box sx={{ pl: 1, pr: 3, height: '100%' }}>
                        {/* <ChatHistory
                      theme={theme}
                      customerId={customerId}
                      data={data}
                    /> */}
                        <Grid
                          container
                          spacing={2}
                          //  ref={wrapper}
                          sx={{ height: '100%' }}
                        >
                          <Grid item xs={12} lg={3} sm={6}>
                            <HoverSocialCard
                              primary="All Orders"
                              secondary={allorders === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : allorders}
                              // percentage={percentage1.toString()}
                              color={theme.palette.primary.main}
                            />
                          </Grid>
                          <Grid item xs={12} lg={3} sm={6}>
                            <HoverSocialCard
                              primary="Pending orders"
                              secondary={uncoveredorders == '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : uncoveredorders}
                              // percentage={percentage2.toString()}
                              color={theme.palette.warning.main}
                            />
                          </Grid>
                          <Grid item xs={12} lg={3} sm={6}>
                            <HoverSocialCard
                              primary="Delivered orders"
                              secondary={coveredorders === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : coveredorders}
                              //  percentage={percentage3.toString()}
                              color={theme.palette.success.main}
                            />
                          </Grid>

                          <Grid item xs={12} lg={3} sm={6}>
                            <HoverSocialCard
                              primary="Cancelled Orders"
                              secondary={cancelled === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : cancelled}
                              // percentage={percentage4.toString()}
                              color={theme.palette.secondary[600]}
                            />
                          </Grid>
                          <Grid
                            item
                            xs={12}
                            sx={{
                              // height: '300px',
                              height: '100%'
                            }}
                          >
                            {/* <ApplicationSales data={custService} /> */}
                            <MainCard
                              title={`Orders- ${datestatus}`}
                              content={false}
                              // secondary={
                              //   // <Link component={RouterLink} to="#" color="primary">
                              //     'View all'
                              //   {/* </Link> */}
                              // }
                              secondary={
                                <Tooltip title="Order Filter">
                                  <IconButton
                                    color="secondary"
                                    variant="light"
                                    sx={{ color: 'text.primary', bgcolor: 'grey.200', display: { xs: 'none', md: 'flex' } }}
                                    aria-haspopup="true"
                                    onClick={() => setOpen(true)}
                                  >
                                    <FilterList />
                                  </IconButton>
                                </Tooltip>
                              }
                            >
                              <Box
                                sx={{
                                  // height: "450px",
                                  height: '430px',

                                  // height: "1515px",
                                  // height: "100%",
                                  overflowY: 'scroll',
                                  scrollbarWidth: 'thin', // Hide scrollbar in Firefox
                                  '&::-webkit-scrollbar': {
                                    width: '3px' // Customize the width of the scrollbar
                                  },
                                  '&::-webkit-scrollbar-thumb': {
                                    backgroundColor: '#65387A', // Customize the scrollbar thumb color
                                    borderRadius: '6px' // Round the scrollbar thumb
                                  },
                                  p: 3,
                                  pt: 0
                                }}
                              >
                                <TableContainer>
                                  <Table>
                                    <TableHead>
                                      <TableRow>
                                        {/* <TableCell >#</TableCell>
            <TableCell align="right">Sales</TableCell>
            <TableCell align="right">Avg. Price</TableCell>
            <TableCell align="right" sx={{ pr: 3 }}>
              Total
            </TableCell> */}
                                        <TableCell sx={{ pl: 3 }}>#</TableCell>
                                        <TableCell>CUSTOMER</TableCell>
                                        <TableCell>ORDER ID</TableCell>
                                        <TableCell>PICKUP</TableCell>
                                        <TableCell>DELIVERY</TableCell>
                                        <TableCell>STATUS</TableCell>
                                      </TableRow>
                                    </TableHead>
                                    <TableBody>
                                      {orderlist.map((row, index) => (
                                        <>
                                          <TableRow hover key={index}>
                                            {/* <TableCell sx={{ pl: 3 }}>
                <Typography align="left" variant="subtitle1">
                  {row.customername}
                </Typography>
                <Typography align="left" variant="caption" color="secondary">
                  {row.contactno}
                </Typography>
              </TableCell> */}
                                            {/* <TableCell align="right">{row.product}</TableCell>
              <TableCell align="right">{row.date}</TableCell>
              <TableCell align="right" sx={{ pr: 3 }}>
                <span>{row.badgeText}</span>
              </TableCell> */}

                                            <TableCell sx={{ pl: 3 }}>{row.sno}</TableCell>
                                            <TableCell align="left" sx={{ paddingLeft: '12px !important' }}>
                                              <Stack direction="row" alignItems="center" spacing={1} justifyContent="flex-start">
                                                <Avatar
                                                  alt=""
                                                  size="sm"
                                                  sx={{
                                                    width: '25px',
                                                    height: '25px'
                                                  }}
                                                ></Avatar>
                                                <Stack direction="column">
                                                  <Typography variant="caption">{row.customername}</Typography>
                                                  <Typography variant="caption" color="textSecondary">
                                                    {row.contactno}
                                                  </Typography>
                                                </Stack>
                                              </Stack>
                                            </TableCell>
                                            <TableCell align="left">
                                              <Typography variant="body2" noWrap>
                                                {row.orderid}
                                              </Typography>
                                              <Typography noWrap sx={{ fontSize: '11px' }}>
                                                {dayjs(row.deliverytime).utc().format('DD/MM/YYYY')}
                                              </Typography>
                                              <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                                                {dayjs(row.deliverytime).utc().format('hh:mm A')}
                                              </Typography>
                                            </TableCell>
                                            <TableCell align="left">
                                              <Stack direction="column">
                                                <Tooltip title={row.pickupaddress}>
                                                  <Typography variant="caption" color="textSecondary" sx={{ cursor: 'pointer' }}>
                                                    {/* {row.pickupaddress.slice(0, 20)} */}
                                                    {row.locationsuburb || row.pickupaddress.slice(0, 20)}
                                                  </Typography>
                                                </Tooltip>
                                              </Stack>
                                            </TableCell>
                                            <TableCell align="left">
                                              <Stack direction="column">
                                                <Tooltip title={row.deliveryaddress}>
                                                  <Typography variant="caption" color="textSecondary" sx={{ cursor: 'pointer' }}>
                                                    {/* {row.deliveryaddress.slice(0, 20)} */}
                                                    {row.customersuburb || row.deliveryaddress.slice(0, 20)}
                                                  </Typography>
                                                </Tooltip>
                                              </Stack>
                                            </TableCell>
                                            {/* <TableCell align="left">{row.ordernotes}</TableCell> */}
                                            <TableCell align="right" sx={{ pr: 3 }}>
                                              <Stack direction="row">
                                                {row.orderstatus === 'pending' && <Chip label="Pending" color="warning" size="small" />}
                                                {row.orderstatus === 'modified' && <Chip label="Confirmed" color="success" size="small" />}
                                                {row.orderstatus === 'cancelled' && <Chip label="Cancelled" color="error" size="small" />}
                                                {row.orderstatus === 'delivered' && <Chip label="Completed" color="primary" size="small" />}
                                                {row.orderstatus === 'processing' && (
                                                  <Chip label="Processing" color="primary" size="small" />
                                                )}
                                                {row.orderstatus === 'ready' && <Chip label="Accepted" color="info" size="small" />}
                                                {row.orderstatus === 'confirmed' && <Chip label="Confirmed" color="success" size="small" />}

                                                {row.orderstatus === 'active' && <Chip label="Picked" color="info" size="small" />}
                                                {row.orderstatus === 'closed' && <Chip label="Closed" color="info" size="small" />}
                                                {row.orderstatus === 'created' && <Chip label="Created" color="secondary" size="small" />}
                                              </Stack>
                                            </TableCell>
                                          </TableRow>
                                        </>
                                      ))}
                                    </TableBody>
                                  </Table>
                                </TableContainer>
                              </Box>
                            </MainCard>
                            {/* <TableContainer>
                              <Table>
                                <TableHead>
                                  <TableRow>
                                    <TableCell>#</TableCell>
                                    <TableCell>CUSTOMER</TableCell>
                                    <TableCell>ORDER ID</TableCell>
                                    <TableCell>PICKUP</TableCell>
                                    <TableCell>DELIVERY</TableCell>
                                    <TableCell>STATUS</TableCell>

                                  </TableRow>
                                </TableHead>
                                <TableBody>

                                  {orderlist.map((row)=>{

                                    return <>
                                      <TableRow>
                                        <TableCell>{row.sno}</TableCell>
                                        <TableCell align="left" sx={{ paddingLeft: '12px !important' }}>

                        <Stack direction="row" alignItems="center" spacing={1} justifyContent="flex-start">
                          <Avatar
                            alt=""
                            size="sm"
                            sx={{
                              width: '25px',
                              height: '25px'
                            }}
                          >

                          </Avatar>
                          <Stack direction="column">
                            <Typography variant="caption">{row.customername}</Typography>
                            <Typography variant="caption" color="textSecondary">

                              {row.contactno}
                            </Typography>
                          </Stack>
                        </Stack>
                      </TableCell>
                      <TableCell align="left">
                        <Typography variant='body2' noWrap>{row.orderid}</Typography>
                        <Typography noWrap
                          sx={{ fontSize: '11px' }}>
                          {dayjs(row.deliverytime).utc().format('DD/MM/YYYY')}
                        </Typography>
                        <Typography noWrap
                          sx={{ fontSize: '11px' }}
                          variant='h5'
                        >
                          {dayjs(row.deliverytime).utc().format('hh:mm A')}
                        </Typography>
                      </TableCell>
                      <TableCell align="left">
                        <Stack direction='column'>
                          <Tooltip title={row.pickupaddress}>
                            <Typography variant="caption" color="textSecondary"
                            >
                              {row.pickupaddress.slice(0, 20)}
                            </Typography>
                          </Tooltip>
                        </Stack>

                      </TableCell>
                      <TableCell align="left">
                        <Stack direction='column'>
                          <Tooltip title={row.deliveryaddress}>
                            <Typography variant="caption" color="textSecondary"
                            >
                              {row.deliveryaddress.slice(0, 20)}
                            </Typography>
                          </Tooltip>
                        </Stack>

                      </TableCell>
                      <TableCell align="left">{row.ordernotes}</TableCell>
                      <TableCell
                       >
                        <Stack direction="row">

                          {(row.orderstatus === 'pending') &&

                            <Chip label="Pending" color="warning" size="small" />
                          }
                          {(row.orderstatus === 'modified') &&
                            <Chip label="Confirmed" color="success" size="small" />
                          }
                          {(row.orderstatus === 'cancelled') &&


                            <Chip label="Cancelled" color="error" size="small" />
                          }
                          {(row.orderstatus === 'delivered') &&

                            <Chip label="Completed" color="primary" size="small" />
                          }
                          {(row.orderstatus === 'processing') &&
                            <Chip label="Processing" color="primary" size="small" />
                          }
                          {(row.orderstatus === 'ready') &&
                            <Chip label="Accepted" color="info" size="small" />
                          }
                          {(row.orderstatus === 'confirmed') &&
                            <Chip label="Confirmed" color="success" size="small" />
                          }

                          {(row.orderstatus === 'active') &&
                            <Chip label="Picked" color="info" size="small" />
                          }
                          {(row.orderstatus === 'closed') &&
                            <Chip label="Closed" color="info" size="small" />
                          }
                          {(row.orderstatus === 'created') &&
                            <Chip label="Created" color="secondary" size="small" />
                          }



                        </Stack>

                      </TableCell>

                                      </TableRow>
                                    </>
                                  })

                                  }

                                </TableBody>
                              </Table>
                            </TableContainer> */}
                          </Grid>
                          {/* </Grid>
                          </Grid> */}
                        </Grid>
                      </Box>
                      {/* </SimpleBar> */}
                    </Grid>
                    {/* <Grid
                item
                xs={12}
                sx={{
                  mt: 3,
                  bgcolor: theme.palette.background.paper,
                  borderTop: `1px solid ${theme.palette.divider}`,
                }}
              >

              </Grid> */}
                  </Grid>
                </MainCard>
              </Grid>
            </Grid>

            {/* </Main> */}
          </Box>
        </Grid>
      </Grid>

      <Dialog open={open}>
        <DialogTitle align="left">
          <Typography variant="h4">Select Filter Options</Typography>
        </DialogTitle>
        <DialogContent sx={{ width: '100%' }} className="datedialog">
          <DateRangePicker
            open={open}
            toggle={() => setOpen(!open)}
            id="daterange1"
            onChange={(range) => {
              if (range.label === 'All') {
                // setDateselect('all');
                setStartdate('');
                setEnddate('');

                setOpen(false);
              } else {
                // setDateselect('select');
                setStartdate(dayjs(range.startDate).format('YYYY-MM-DD'));
                setEnddate(dayjs(range.endDate).format('YYYY-MM-DD'));
                if (range.label) {
                  setDatestatus(range.label);
                } else {
                  setDatestatus(`[${dayjs(range.startDate).format('DD-MM-YYYY')} to ${dayjs(range.endDate).format('DD-MM-YYYY')}]`);
                }
              }
              console.log(range);
            }}
            definedRanges={[
              {
                label: 'Today',
                startDate: new Date(),
                endDate: new Date()
              },
              {
                label: 'Yesterday',
                startDate: addDays(new Date(), -1),
                endDate: addDays(new Date(), -1)
              },
              {
                label: 'Tomorrow',
                startDate: addDays(new Date(), +1),
                endDate: addDays(new Date(), +1)
              },
              {
                label: 'This Week',
                startDate: startOfWeek(new Date()),
                endDate: endOfWeek(new Date())
              },
              {
                label: 'Last Week',
                startDate: startOfWeek(addWeeks(new Date(), -1)),
                endDate: endOfWeek(addWeeks(new Date(), -1))
              },
              {
                label: 'Last 7 Days',
                startDate: addWeeks(new Date(), -1),
                endDate: new Date()
              },
              {
                label: 'This Month',
                startDate: startOfMonth(new Date()),
                endDate: endOfMonth(new Date())
              },
              {
                label: 'Last Month',
                startDate: startOfMonth(addMonths(new Date(), -1)),
                endDate: endOfMonth(addMonths(new Date(), -1))
              }
              // {
              //   label: 'All',
              //   startDate: new Date(),
              //   endDate: addDays(new Date(), -1),
              // },
            ]}
          />
        </DialogContent>
        <Stack direction="row" justifyContent="flex-end" sx={{ width: '100%', p: 2 }}>
          <Button
            variant="contained"
            size="small"
            // onClick={okclicked}
            onClick={() => {
              setOpen(false);
            }}
          >
            ok
          </Button>
        </Stack>
      </Dialog>
    </>
  );
};

export default Customers;
