import React from 'react';
import { Avatar, Tooltip } from '@mui/material';
import { useEffect, useRef, useState, Fragment, useMemo } from 'react';
import { useTheme } from '@mui/material/styles';
import Skeleton from '@mui/material/Skeleton';
import Loader from 'components/Loader';
import { FilterList } from '@mui/icons-material';
import { FaRegEdit } from 'react-icons/fa';
import { RiEdit2Fill } from 'react-icons/ri';
import { enqueueSnackbar } from 'notistack';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import {
  Box,
  Button,
  IconButton,
  Dialog,
  Grid,
  Menu,
  MenuItem,
  Stack,
  TextField,
  Typography,
  Chip,
  OutlinedInput,
  InputAdornment,
  List,
  Divider,
  ListItemButton,
  ListItemAvatar,
  ListItemText,
  DialogTitle,
  DialogContent,
  DialogActions,
  Table,
  TableContainer,
  TableHead,
  TableCell,
  TableBody,
  TableRow,
  Autocomplete,
  Drawer
} 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 { MoreOutlined, SearchOutlined, DeleteFilled } from '@ant-design/icons';
import axios from 'axios';
import HoverSocialCard from 'components/cards/statistics/HoverSocialCard';
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';
import Titlecard from 'components/nearle_components/Titlecard';
import { Empty } from 'antd';

// ==============================|| 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 Customers = () => {
  const drawerWidth = 270;
  const theme = useTheme();
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState([]);
  const [userName, setUserName] = useState('');
  const [contactno, setContactno] = useState('');
  const [open, setOpen] = React.useState(false);
  const [drawerOpen, setDrawerOpen] = React.useState(true);
  const [open3, setOpen3] = React.useState(false);
  const [updateDialog, setUpdateDialog] = React.useState(false);
  const [selectedCustomer, setSelectedCustomer] = useState({}); // to edit
  const [orderlist, setOrderlist] = useState([]);
  const [allorders, setAllorders] = useState('');
  const [coveredorders, setCoveredorders] = useState('');
  const [uncoveredorders, setUncoveredorders] = useState('');
  const [cancelled, setCancelled] = 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({});

  const toggleDrawer = () => {
    setDrawerOpen((prev) => !prev);
  };

  // ==============================|| 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 = () => {
    setUpdateDialog(true);
  };

  const handleClose4 = () => {
    setUpdateDialog(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 handleClose = () => {
    setOpen3(false);
  };
  useEffect(() => {
    console.log('username', userName);
  }, [userName]);

  const [anchorEl, setAnchorEl] = useState();

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

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

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

  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}/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 }];
            });
            setSelectedCustomer(arr[0]);
            setUsers([...arr]);
            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 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);
    }
  };

  function AlertCustomerDelete({
    // title,
    open,
    handleClose
  }) {
    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>

            <Stack spacing={2}>
              <Typography variant="h4" align="center">
                Are you sure you want to Remove this Customer?
              </Typography>
            </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 && <Loader />}
      <AlertCustomerDelete open={open3} handleClose={handleClose} />
      <Titlecard title={'Customers'} />
      <Box
        sx={{
          display: 'flex',
          height: 'calc(100vh - 160px)',
          overflow: 'hidden',
          borderRadius: 2,
          boxShadow: 1,
          border: '1px solid #ddd'
        }}
      >
        {/* Drawer Section */}
        <Drawer
          variant="permanent"
          open={drawerOpen}
          PaperProps={{
            sx: {
              position: 'relative',
              width: drawerWidth,
              boxSizing: 'border-box',
              transition: 'width 0.3s ease',
              overflowX: 'hidden',
              zIndex: 0,
              ...(drawerOpen ? {} : { width: 0 })
            }
          }}
        >
          <Stack sx={{ backgroundColor: 'white', borderRadius: 1, overflow: 'hidden' }}>
            {/* Search bar */}
            <Box sx={{ p: 2, zIndex: 10 }}>
              <OutlinedInput
                inputRef={textFieldRef}
                fullWidth
                placeholder="Search (ctrl+k)"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                startAdornment={
                  <InputAdornment position="start">
                    <SearchOutlined style={{ fontSize: 'small' }} />
                  </InputAdornment>
                }
                endAdornment={
                  <Tooltip title="Clear">
                    <IconButton sx={{ visibility: search ? 'visible' : 'hidden' }} onClick={() => setSearch('')}>
                      <ClearIcon />
                    </IconButton>
                  </Tooltip>
                }
              />
            </Box>
            <Divider />
            {/* Scrollable User List */}
            <Box
              sx={{
                height: '600px',
                overflowY: 'auto',

                scrollbarWidth: 'thin',
                '&::-webkit-scrollbar': {
                  width: '3px'
                },
                '&::-webkit-scrollbar-thumb': {
                  backgroundColor: '#65387A',
                  borderRadius: '6px'
                }
              }}
            >
              {loading1 ? (
                [...Array(9)].map((_, i) => (
                  <Stack direction="row" spacing={2} key={i} sx={{ mb: 2 }}>
                    <Skeleton variant="circular" width={40} height={40} />
                    <Stack sx={{ flexGrow: 1 }}>
                      <Skeleton variant="text" sx={{ fontSize: '1rem' }} />
                      <Skeleton variant="text" sx={{ fontSize: '1rem' }} />
                    </Stack>
                  </Stack>
                ))
              ) : (
                <List component="nav">
                  {users.map((user) => (
                    <Fragment key={user.sno}>
                      <ListItemButton
                        sx={{ pl: 3 }}
                        onClick={() => {
                          setTenid(user.customerid);
                          setUserName(user.firstname);
                          setContactno(user.contactno);
                          fetchData(user.customerid);
                          fetchpercentage(user.customerid);
                          setSelectedCustomer(user);
                        }}
                      >
                        <ListItemAvatar>
                          <Avatar style={{ background: '#65387A' }} />
                        </ListItemAvatar>
                        <ListItemText
                          primary={
                            <Stack direction="row" justifyContent="space-between" alignItems="center">
                              <Typography variant="h6" noWrap sx={{ maxWidth: '75%' }}>
                                {user.firstname}
                              </Typography>
                              <Typography variant="caption" color="textSecondary">
                                {/* Timestamp or status here */}
                              </Typography>
                            </Stack>
                          }
                          secondary={
                            <Typography variant="caption" color="textSecondary" noWrap>
                              {user.contactno}
                            </Typography>
                          }
                        />
                      </ListItemButton>
                      <Divider />
                    </Fragment>
                  ))}
                </List>
              )}
            </Box>
          </Stack>

          <Box sx={{ width: '100%', p: 2 }}>
            <Stack direction={'row'} justifyContent={'flex-end'}>
              <Typography variant="h6">{users.length} Customers</Typography>
            </Stack>
          </Box>
        </Drawer>
        {/* Content Section */}
        <Stack sx={{ width: '100%' }}>
          <Stack sx={{ mx: 1, my: 1.8 }}>
            <Grid container justifyContent="space-between">
              <Grid item sx={{}}>
                <Stack direction="row" alignItems="center" spacing={2}>
                  <IconButton
                    onClick={toggleDrawer}
                    sx={{
                      color: '#65387A',
                      bgcolor: 'transparent',

                      fontSize: '25px',
                      ':hover': {
                        color: '#65387A',
                        bgcolor: 'transparent'
                      }
                    }}
                  >
                    {/* <MenuIcon /> */}
                    {!drawerOpen ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                  </IconButton>
                  <Avatar
                    sx={{
                      bgcolor: '#65387A',

                      fontSize: 20
                    }}
                  >
                    {userName?.charAt(0).toUpperCase()}
                  </Avatar>
                  {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={{}}>
                <Stack direction="row" alignItems="center" spacing={2} sx={{ height: '100%', mr: 1 }}>
                  <Chip label={`Orders- ${datestatus}`} />
                  <Tooltip title="Order Filter">
                    <IconButton
                      color="secondary"
                      variant="light"
                      sx={{ color: 'text.primary', bgcolor: 'grey.200' }}
                      aria-haspopup="true"
                      onClick={() => setOpen(true)}
                    >
                      <FilterList />
                    </IconButton>
                  </Tooltip>
                  <IconButton
                    onClick={handleClickSort}
                    color="secondary"
                    variant="light"
                    sx={{ color: 'text.primary', bgcolor: 'grey.200' }}
                    aria-haspopup="true"
                  >
                    <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>
                    </MenuItem>
                    <MenuItem onClick={handleCloseSort}>
                      <Button
                        variant="text"
                        onClick={() => {
                          handleClickOpen4();
                        }}
                      >
                        {
                          <RiEdit2Fill
                            style={{
                              fontSize: '12px',
                              marginRight: '15px'
                            }}
                          />
                        }
                        Edit
                      </Button>
                    </MenuItem>
                  </Menu>
                </Stack>
              </Grid>
            </Grid>
          </Stack>
          <Divider />
          <Stack sx={{ m: 1 }}>
            <Grid container spacing={2} sx={{ height: '100%' }}>
              <Grid item xs={6} lg={3} sm={3}>
                <HoverSocialCard
                  primary="All "
                  secondary={allorders === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : allorders}
                  color={theme.palette.primary.main}
                />
              </Grid>
              <Grid item xs={6} lg={3} sm={3}>
                <HoverSocialCard
                  primary="Pending "
                  secondary={uncoveredorders == '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : uncoveredorders}
                  color={theme.palette.warning.main}
                />
              </Grid>
              <Grid item xs={6} lg={3} sm={3}>
                <HoverSocialCard
                  primary="Delivered "
                  secondary={coveredorders === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : coveredorders}
                  color={theme.palette.success.main}
                />
              </Grid>
              <Grid item xs={6} lg={3} sm={3}>
                <HoverSocialCard
                  primary="Cancelled "
                  secondary={cancelled === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : cancelled}
                  color={theme.palette.secondary[600]}
                />
              </Grid>
            </Grid>
          </Stack>
          <Stack sx={{ height: '100%' }}>
            <TableContainer sx={{ height: '100%' }}>
              <Table sx={{ height: '100%' }}>
                <TableHead>
                  <TableRow>
                    <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 || orderlist.length == 0) && (
                    <TableRow>
                      <TableCell colSpan={6}>
                        <Empty description="No Orders" />
                      </TableCell>
                    </TableRow>
                  )}
                  {orderlist?.map((row, index) => (
                    <>
                      <TableRow hover key={index}>
                        <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.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.customersuburb || row.deliveryaddress.slice(0, 20)}
                              </Typography>
                            </Tooltip>
                          </Stack>
                        </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>
          </Stack>
        </Stack>
      </Box>
      {/* ======================================== || Edit Dialog || ======================================== */}
      <Dialog
        open={updateDialog}
        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>
      {/* ========================================================= || Date Filter || ============================================================== */}
      <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={() => {
              setOpen(false);
            }}
          >
            ok
          </Button>
        </Stack>
      </Dialog>
    </>
  );
};

export default Customers;
