import * as React from 'react';
import { enqueueSnackbar } from 'notistack';
import { DeleteFilled, NotificationOutlined } from '@ant-design/icons';
import { useState, useEffect, Fragment, useRef } from 'react';
import { Empty } from 'antd';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import dayjs from 'dayjs';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
import axios from 'axios';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
// import { DataGrid } from '@mui/x-data-grid'
// material-ui
import HoverSocialCard from 'components/cards/statistics/HoverSocialCard';
// import {FacebookOutlined}  from '@ant-design/icons';
import { useTheme } from '@mui/material/styles';
// import { edittabstatus1 } from 'store/reducers/dashboard1';
import {
  Avatar,
  // AvatarGroup,
  // Button as Button1,
  Box,
  // DateRangePicker,
  Button,
  Grid,
  Tabs,
  Tab,
  IconButton,
  Stack,
  // TextField,
  Chip,
  // TableSortLabel,
  Typography,
  // Divider,
  Table,
  TableCell,
  TableBody,
  TableHead,
  // TableSortLabel,
  Collapse,
  Dialog,
  TableRow,
  DialogContent,
  DialogTitle,
  Tooltip,
  FormControl,
  OutlinedInput,
  InputAdornment,
  Skeleton,
  CircularProgress,
  DialogActions
} from '@mui/material';
import MainCard from 'components/MainCard';

import { SearchOutlined, CloseOutlined } from '@ant-design/icons';
import ClearIcon from '@mui/icons-material/Clear';

import {
  addDays,
  addMonths,
  addWeeks,
  // addYears,
  endOfMonth,
  endOfWeek,
  // endOfYear,
  startOfMonth,
  startOfWeek
  // startOfYear,
} from 'date-fns';

import { DateRangePicker } from 'mui-daterange-picker';
import { useNavigate } from 'react-router';
import PropTypes from 'prop-types';
import TableContainer from '@mui/material/TableContainer';
import TablePagination from '@mui/material/TablePagination';
import TableSortLabel from '@mui/material/TableSortLabel';
import { visuallyHidden } from '@mui/utils';
import Loader from 'components/Loader';
import { FilterList } from '@mui/icons-material';

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

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

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

  const headCells = [
    {
      id: 'sno',
      disablePadding: true,
      label: 'S NO'
    },
    // {
    //   id: 'tenantname',
    //   numeric: false,
    //   disablePadding: false,
    //   label: 'CUSTOMER',
    // },
    {
      id: 'orderid',
      numeric: false,
      disablePadding: false,
      label: 'ORDER ID'
    },
    {
      id: 'eventname',
      disablePadding: false,
      label: 'Pickup'
    },
    {
      id: 'eventname4',
      disablePadding: false,
      label: 'Delivery'
    },
    //   {
    //     id: 'ordervalue',
    //     disablePadding: false,
    //     label: 'VALUE $',
    //   },
    {
      id: 'itemcount',
      disablePadding: false,
      label: 'NOTES'
    },
    {
      id: 'orderstatus',
      disablePadding: false,
      label: 'STATUS'
    },
    {
      id: 'action',
      disablePadding: false,
      label: 'ACTION'
    }
  ];

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

    return (
      <TableHead>
        <TableRow>
          {headCells.map((headCell) => (
            <TableCell
              key={headCell.id}
              align={headCell.numeric ? 'right' : 'left'}
              padding={headCell.disablePadding ? 'none' : 'normal'}
              sortDirection={orderBy === headCell.id ? order : false}
            >
              <TableSortLabel
                active={orderBy === headCell.id}
                direction={orderBy === headCell.id ? order : 'asc'}
                onClick={createSortHandler(headCell.id)}
              >
                {headCell.label}
                {orderBy === headCell.id ? (
                  <Box component="span" sx={visuallyHidden}>
                    {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
                  </Box>
                ) : null}
              </TableSortLabel>
            </TableCell>
          ))}
        </TableRow>
      </TableHead>
    );
  }

  EnhancedTableHead.propTypes = {
    numSelected: PropTypes.number.isRequired,
    onRequestSort: PropTypes.func.isRequired,
    onSelectAllClick: PropTypes.func.isRequired,
    order: PropTypes.oneOf(['asc', 'desc']).isRequired,
    orderBy: PropTypes.string.isRequired,
    rowCount: PropTypes.number.isRequired
  };

  function EnhancedTable() {
    const [order, setOrder] = React.useState('asc');
    const [orderBy, setOrderBy] = React.useState('calories');
    const [selected, setSelected] = React.useState([]);
    const [page, setPage] = React.useState(0);
    const [rowsPerPage, setRowsPerPage] = React.useState(10);
    const [expandopen, setExpandopen] = React.useState('');

    const [dialogopen, setDialogopen] = useState(false);
    const [stafflist, setStafflist] = useState([]);
    const [loading1, setLoading1] = useState(false);
    const [open, setOpen] = useState(false);
    const [orderheaderid, setOrderheaderid] = useState('');

    const cancelorder = async () => {
      await axios
        .put(`${process.env.REACT_APP_URL}/orders/updateorder`, {
          orderheaderid: orderheaderid,
          orderstatus: 'cancelled',
          cancelled: dayjs().format('YYYY-MM-DD HH:mm:ss')
        })
        .then((res) => {
          console.log(res);
          if (res.data.status) {
            // if (orderheaderid && tenantid) {
            //   fetchorderdetails();
            //   fetchorderaddons();
            //   fetchorderattires();
            // }
            enqueueSnackbar('Order Cancelled Successfully', {
              variant: 'success',
              anchorOrigin: { vertical: 'top', horizontal: 'right' },
              autoHideDuration: 2000
            });
            handleClose(true);

            if (localStorage.getItem('tenantid')) {
              setTenantid(localStorage.getItem('tenantid'));
              let val = localStorage.getItem('tenantid');

              fetchtable(val);
              fetchpercentage(val);
              fetchtableuncovered(val);
              fetchtablecovered(val);
              fetchtablecancelled(val);
              // fetchtableassigned(val);
              // fetchtablepicked(val);
              fetchtablecreated(val);
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };

    const fetchstafflist = async (odid) => {
      setLoading1(true);
      try {
        await axios
          .get(`${process.env.REACT_APP_URL2}/orders/getassignedinfo?orderdetailid=${odid}`)

          .then((res) => {
            console.log(res);
            if (res.data.status) {
              setStafflist(res.data.Details);
            }

            setLoading1(false);
          })
          .catch((err) => {
            console.log(err);
            setLoading1(false);
          });
      } catch (err) {
        console.log(err);
        setLoading1(false);
      }
    };

    const dialogclose = () => {
      setDialogopen(false);
    };

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

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

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

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

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

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

    const visibleRows = React.useMemo(
      () => stableSort(rows, getComparator(order, orderBy)).slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage),
      [order, orderBy, page, rowsPerPage]
    );

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

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

      return (
        <Dialog
          open={open}
          onClose={() => handleClose(false)}
          // keepMounted
          // TransitionComponent={PopupTransition}
          maxWidth="xs"
          // aria-labelledby="column-delete-title"
          // aria-describedby="column-delete-description"
        >
          <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 cancel this order?
                </Typography>

                {/* <Typography variant="h4" align="center">
                    Please type in the order number to confirm.
                  </Typography> */}
              </Stack>

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

    return (
      <Box sx={{ width: '100%' }}>
        <AlertCustomerDelete open={open} handleClose={handleClose} />

        <TableContainer sx={{ width: '100%', borderBottom: 1, borderColor: 'divider' }}>
          <Table sx={{ minWidth: 750 }} aria-label="collapsible table" size={'medium'}>
            <EnhancedTableHead
              numSelected={selected.length}
              order={order}
              orderBy={orderBy}
              onSelectAllClick={handleSelectAllClick}
              onRequestSort={handleRequestSort}
              rowCount={rows.length}
            />
            {loading && (
              <>
                <TableBody>
                  {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((item, index) => (
                    <TableRow key={index}>
                      <TableCell>
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </>
            )}
            <TableBody>
              {visibleRows.length == 0 && !loading && (
                <>
                  <TableCell colSpan={7}>
                    <Stack width={'100%'} direction={'row'} justifyContent={'center'}>
                      <Empty />
                    </Stack>
                  </TableCell>
                  {/* <div>empty</div> */}
                </>
              )}

              {visibleRows.map((row, index) => {
                const isItemSelected = isSelected(row.sno);
                const labelId = `enhanced-table-checkbox-${index}`;

                return (
                  <>
                    <TableRow
                      role="checkbox"
                      aria-checked={isItemSelected}
                      tabIndex={-1}
                      key={row.sno}
                      sx={{
                        cursor: 'pointer',

                        backgroundColor: expandopen === row.sno ? '#f5f5f5' : ''
                      }}
                    >
                      <TableCell component="th" id={labelId} scope="row" padding="none">
                        <Typography> {row.sno}</Typography>
                      </TableCell>

                      <TableCell align="left">
                        <Typography variant="body2" noWrap>
                          {row.orderid}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '11px' }}>
                          {dayjs(row.deliverydate).utc().format('DD/MM/YYYY')}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                          {dayjs(row.deliverydate).utc().format('hh:mm A')}
                        </Typography>
                      </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">
                        <Stack direction={'row'} spacing={1}>
                          <Avatar
                            alt=""
                            size="sm"
                            sx={{
                              width: '25px',
                              height: '25px'
                            }}
                          ></Avatar>
                          <Stack direction="column">
                            <Typography variant="caption">{row.pickupcustomer}</Typography>
                            <Typography variant="caption" color="textSecondary">
                              {row.pickupcontactno}
                            </Typography>
                            <Tooltip title={row.pickupaddress}>
                              <Typography variant="caption" color="textSecondary">
                                {/* {row.pickupaddress.slice(0, 20)} */}
                                {row.pickupsuburb || row.pickupaddress.slice(0, 20)}
                              </Typography>
                            </Tooltip>
                          </Stack>
                        </Stack>
                        {/* <Stack direction='column'>

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

                            </Typography>
                          </Tooltip>
                        </Stack> */}
                        <Stack direction={'row'} spacing={1}>
                          <Avatar
                            alt=""
                            size="sm"
                            sx={{
                              width: '25px',
                              height: '25px'
                            }}
                          ></Avatar>
                          <Stack direction="column">
                            <Typography variant="caption">{row.deliverycustomer}</Typography>
                            <Typography variant="caption" color="textSecondary">
                              {row.deliverycontactno}
                            </Typography>
                            <Tooltip title={row.deliveryaddress}>
                              <Typography variant="caption" color="textSecondary">
                                {/* {row.pickupaddress.slice(0, 20)} */}
                                {row.deliverysuburb || row.deliveryaddress.slice(0, 20)}
                              </Typography>
                            </Tooltip>
                          </Stack>
                        </Stack>
                      </TableCell>
                      <TableCell align="left">{row.ordernotes}</TableCell>
                      {/* <TableCell align="left"><Chip label={row.itemcount} color="primary" variant="light" size="small" /></TableCell> */}
                      <TableCell align="left">
                        <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>

                      <TableCell>
                        {row.orderstatus == 'created' && (
                          <>
                            <Tooltip title="Cancel">
                              <IconButton
                                // disabled={(row.orderstatus != 'created')}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  setOrderheaderid(row.orderheaderid);
                                  setOpen(true);
                                  // navigate(`/details`, {
                                  //   state: {
                                  //     orderheaderid: row.orderheaderid,
                                  //     tenantid: row.tenantid
                                  //   }
                                  // })
                                }}
                              >
                                {/* <EyeTwoTone twoToneColor={theme.palette.secondary.main} /> */}
                                <CloseOutlined
                                  style={{
                                    color: theme.palette.error.main
                                  }}
                                  //  twoToneColor={theme.palette.primary.main}
                                />
                              </IconButton>
                            </Tooltip>
                          </>
                        )}
                      </TableCell>
                    </TableRow>
                    <TableRow>
                      <TableCell
                        style={{ paddingBottom: 0, paddingTop: 0, paddingLeft: 0, paddingRight: 0 }}
                        colSpan={8}
                        sx={{ width: '100%' }}
                      >
                        <Collapse in={expandopen === row.sno} timeout="auto" unmountOnExit>
                          {/* <Grid container sx={{ width: '100%' }}>
                              {(row.ordershifts).map((val5, k) => {
                                return <>
                                  <Grid item sx={{ width: '100%', m: 1 }}>
                                    <MainCard sx={{
                                      opacity: ((val5.shiftstatus == 1) || (val5.status == 1)) ? '0.6' : ''

                                    }}>

                                      <Stack direction={{ xs: 'column', md: 'row' }} spacing={2} sx={{ p: 2 }} alignItems={{ md: 'center' }}>
                                        <Typography>Shift {k + 1}</Typography>

                                        <Typography color="secondary"  >
                                          <EnvironmentOutlined /> {''}{val5.locationaddress}
                                        </Typography>
                                        <Grid item>
                                          {((val5.shiftstatus == 1) || (val5.status == 1)) &&
                                            <Chip label="Cancelled" color='secondary' />
                                          }
                                        </Grid>
                                      </Stack>


                                      <TableContainer  >
                                        <Table sx={{ width: '100%' }} >
                                          <TableHead >
                                            <TableRow

                                            >
                                              <TableCell></TableCell>
                                              <TableCell>#</TableCell>
                                              <TableCell>Role</TableCell>
                                              <TableCell>Start Date</TableCell>
                                              <TableCell>End Date</TableCell>
                                              <TableCell>Unpaid break</TableCell>
                                              <TableCell align="center">Count</TableCell>
                                              <TableCell align="center">Assigned</TableCell>
                                              <TableCell align="right">Price</TableCell>
                                              <TableCell align="right">Amount</TableCell>
                                              <TableCell align="left">Assigned Roles</TableCell>


                                            </TableRow>
                                          </TableHead>
                                          <TableBody>

                                            {((val5.orderdetails) ? val5.orderdetails : []).map((val, i) => {

                                              return <>

                                                <TableRow key={i}

                                                  sx={{
                                                    opacity: (val.status == 0) ? '' : '0.6'
                                                  }}
                                                >
                                                  <TableCell></TableCell>
                                                  <TableCell>{i + 1}</TableCell>
                                                  <TableCell>
                                                    {val.productname}
                                                  </TableCell>

                                                  <TableCell>
                                                    <Stack direction="column">
                                                      <Typography variant="body1">
                                                        {dayjs(val.starttime).format('MM/DD/YYYY')}
                                                      </Typography>
                                                      <Typography variant="body2">
                                                        {dayjs(val.starttime).format('hh:mm A')}
                                                      </Typography>
                                                    </Stack>
                                                  </TableCell>
                                                  <TableCell>
                                                    {' '}
                                                    <Stack direction="column">
                                                      <Typography variant="body1">
                                                        {dayjs(val.endtime).format('MM/DD/YYYY')}
                                                      </Typography>
                                                      <Typography variant="body2">
                                                        {dayjs(val.endtime).format('hh:mm A')}
                                                      </Typography>
                                                    </Stack>
                                                  </TableCell>
                                                  <TableCell>
                                                    {val.unpaidbreak || 0}
                                                  </TableCell>
                                                  <TableCell align="center">
                                                    <Chip label={val.orderqty} color="primary" variant="light" size="small" />

                                                  </TableCell>
                                                  <TableCell align="center">
                                                    <Chip label={val.supplyqty} color={(val.supplyqty > 0) ? "warning" : "error"} variant="light" size="small" />
                                                  </TableCell>
                                                  <TableCell align="right">${val.price}</TableCell>
                                                  <TableCell align="right">${val.landingamount}</TableCell>
                                                  <TableCell >

                                                    <Tooltip title='Assigned staffs'>
                                                      <Button sx={{ minWidth: '10px !important' }}
                                                        onClick={(e) => {
                                                          e.stopPropagation();
                                                          setStafflist([])
                                                          fetchstafflist(val.orderdetailid)
                                                          setDialogopen(true)
                                                        }}
                                                      >
                                                        <UserOutlined />
                                                      </Button>
                                                    </Tooltip>
                                                  </TableCell>

                                                </TableRow>
                                              </>

                                            })}

                                          </TableBody>
                                        </Table>
                                      </TableContainer >
                                    </MainCard>
                                  </Grid>





                                  <Dialog maxWidth={false} fullWidth={true}
                                    open={dialogopen} onClose={dialogclose}

                                    scroll={'paper'}
                                    TransitionComponent={PopupTransition}>

                                    <DialogTitle>
                                      <Stack direction={'row'} justifyContent={'space-between'}>
                                        <Stack direction={{
                                          xs: 'column'
                                        }} spacing={2} alignItems={'flex-start'}>
                                          <Typography variant='h3'>Assigned Roles</Typography>
                                          {(stafflist[0]) &&

                                            <Chip icon={<EnvironmentOutlined />} label={stafflist[0].locationaddress} variant="light" color="primary" />
                                          }
                                        </Stack>
                                        {(stafflist[0]) &&
                                          <Chip label={stafflist[0].orderid} variant="combined" color='warning' size={'large'} />

                                        }

                                      </Stack>
                                      <Grid container sx={{ p: 1 }} spacing={2}>

                                        <Grid item sm={6} xs={12}>


                                        </Grid>
                                        <Grid item sm={6} xs={12}>


                                        </Grid>
                                      </Grid>
                                    </DialogTitle>
                                    <DialogContent dividers={true}>

                                      {(stafflist.length === 0) ?
                                        <>
                                          {(loading1) ?
                                            <>


                                              <Stack alignItems={'center'}>
                                                <CircularProgress />
                                              </Stack>

                                            </>
                                            :
                                            <Typography>No Staffs has been Assigned</Typography>

                                          }
                                        </>
                                        :

                                        <TableContainer>
                                          <Table>
                                            <TableHead>
                                              <TableRow>
                                                <TableCell>#</TableCell>
                                                <TableCell>Staff</TableCell>
                                                <TableCell>Start Time</TableCell>
                                                <TableCell>End Time</TableCell>
                                                <TableCell>Pay Rate</TableCell>

                                                <TableCell align='center'>Clockin</TableCell>
                                                <TableCell align='center'>Clockout</TableCell>

                                                <TableCell>Hours Worked</TableCell>


                                                <TableCell>Status</TableCell>

                                              </TableRow>
                                            </TableHead>
                                            <TableBody>
                                              {stafflist.map((val, i) => {

                                                return <Fragment key={i}>


                                                  <TableRow sx={{

                                                  }}>
                                                    <TableCell component="th"
                                                      scope="row" padding="none">
                                                      {i + 1}
                                                    </TableCell>

                                                    <TableCell align="left">
                                                      <Stack direction="column">
                                                        <Typography variant="caption">
                                                          {val.staffname}
                                                        </Typography>
                                                        <Grid>
                                                          <Chip label={val.productname} color="info" variant="light" size="small" />
                                                        </Grid>
                                                      </Stack>
                                                    </TableCell>
                                                    <TableCell>
                                                      <Stack direction="column">
                                                        <Typography variant="body2">{dayjs(val.Starttime).format('MM/DD/YYYY')}</Typography>
                                                        <Typography variant="caption">{dayjs(val.Starttime).format('hh:mm A')}</Typography>
                                                      </Stack>
                                                    </TableCell>
                                                    <TableCell>
                                                      <Stack direction="column">
                                                        <Typography variant="body2">{dayjs(val.Endtime).format('MM/DD/YYYY')}</Typography>
                                                        <Typography variant="caption">{dayjs(val.Endtime).format('hh:mm A')}</Typography>
                                                      </Stack>
                                                    </TableCell>
                                                    <TableCell>{val.rolecost}</TableCell>


                                                    <TableCell>
                                                      <Stack spacing={0.5}
                                                        alignItems="center"
                                                      >

                                                        <Chip label={(val.clockin) ? dayjs(val.clockin).format('MM/DD/YYYY') : ''} color="primary" variant="light" size="small" />
                                                        <Chip label={(val.clockin) ? dayjs(val.clockin).format('hh:mm A') : ''} color="info" variant="light" size="small" />

                                                      </Stack>
                                                    </TableCell>
                                                    <TableCell>
                                                      <Stack spacing={0.5}
                                                        alignItems="center"
                                                      >

                                                        <Chip label={(val.clockout) ? dayjs(val.clockout).format('MM/DD/YYYY') : ''} color="primary" variant="light" size="small" />
                                                        <Chip label={(val.clockout) ? dayjs(val.clockout).format('hh:mm A') : ''} color="info" variant="light" size="small" />

                                                      </Stack>
                                                    </TableCell>
                                                    <TableCell>
                                                      {val.hoursworked}
                                                    </TableCell>



                                                    <TableCell align="left">
                                                      <Stack direction="row">

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

                                                          <Chip label="Pending" color="error" size="small" />
                                                        }
                                                        {(val.orderstatus === 'cancelled') &&


                                                          <Chip label="Cancelled" color="secondary" size="small" />
                                                        }
                                                        {(val.orderstatus === 'completed') &&

                                                          <Chip label="Completed" color="primary" size="small" />
                                                        }
                                                        {(val.orderstatus === 'processing') &&
                                                          <Chip label="Processing" color="primary" size="small" />
                                                        }
                                                        {(val.orderstatus === 'assigned') &&
                                                          <Chip label="Assigned" color="warning" size="small" />
                                                        }
                                                        {(val.orderstatus === 'confirmed') &&
                                                          <Chip label="Confirmed" color="success" size="small" />
                                                        }

                                                        {(val.orderstatus === 'active') &&
                                                          <Chip label="Active" color="info" size="small" />
                                                        }
                                                        {(val.orderstatus === 'closed') &&
                                                          <Chip label="Closed" color="info" size="small" />
                                                        }
                                                      </Stack>

                                                    </TableCell>
                                                  </TableRow>
                                                </Fragment>

                                              })
                                              }
                                            </TableBody>
                                          </Table>
                                        </TableContainer>
                                      }
                                    </DialogContent>
                                    <DialogActions>
                                      <Stack sx={{ mt: 2 }} direction='row' justifyContent='flex-end' spacing={5}>

                                        <Button sx={{ width: '130px' }} color='error' variant='contained' onClick={() => { dialogclose() }}>Close</Button>
                                      </Stack>
                                    </DialogActions>
                                  </Dialog >
                                </>
                              })


                              }


                            </Grid> */}
                        </Collapse>
                      </TableCell>
                    </TableRow>
                  </>
                );
              })}
              {emptyRows > 0 && (
                <TableRow
                  style={{
                    height: 53 * emptyRows
                  }}
                >
                  <TableCell colSpan={8} />
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
        <TablePagination
          rowsPerPageOptions={[10, 25, 50, 100]}
          component="div"
          count={rows.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        />
      </Box>
    );
  }

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

  const [tenantid, setTenantid] = useState('');

  const [percentage1, setPercentage1] = useState('0');
  const [percentage2, setPercentage2] = useState('0');
  const [percentage3, setPercentage3] = useState('0');
  const [percentage4, setPercentage4] = useState('0');
  let [orderarr, setArr] = useState([]);
  let [orderarrcovered, setArrcovered] = useState([]);
  let [orderarractive, setArractive] = useState([]);
  let [orderarruncovered, setArruncovered] = useState([]);
  let [orderarrcancelled, setArrcancelled] = useState([]);
  let [orderarrassigned, setArrassigned] = useState([]);
  let [orderarrconfirmed, setArrconfirmed] = useState([]);
  let [orderarrmodified, setArrmodified] = useState([]);
  let [orderarrclosed, setArrclosed] = useState([]);
  let [orderarrpicked, setArrpicked] = useState([]);
  let [orderarrcreated, setArrcreated] = useState([]);

  const [allorders, setAllorders] = useState('');
  const [activeorders, setActiveorders] = useState('');
  const [coveredorders, setCoveredorders] = useState('');
  const [uncoveredorders, setUncoveredorders] = useState('');
  const [cancelled, setCancelled] = useState('');

  const [assigned, setAssigned] = useState('');
  const [confirmed, setConfirmed] = useState('');
  const [modified, setModified] = useState('');
  const [completed, setCompleted] = useState('');
  const [closed, setClosed] = useState('');
  const [picked, setPicked] = useState('');
  const [created, setCreated] = useState('');
  const [tabstatus, setTabstatus] = useState('Created');
  const [loading, setLoading] = useState(true);
  const theme = useTheme();
  let [rows, setRows] = useState([]);
  const [tabvalue, setTabvalue] = useState(0);
  let navigate = useNavigate();
  const [open, setOpen] = useState(false);
  const [dateselect, setDateselect] = useState('select');
  // const [tabstatus1, setTabstatus1] = useState('All');
  const [tabstatus1, setTabstatus1] = useState('Today');

  // const [datestatus, setDatestatus] = useState('All');
  const [datestatus, setDatestatus] = useState('Today');

  const [searchword, setSearchword] = useState('');

  const handleChangetab = (e, i) => {
    setTabvalue(i);

    // if (i === 0) setTabstatus('All orders')
    if (i === 0) setTabstatus('Created');
    // if (i === 2) setTabstatus('Modified')
    if (i === 1) setTabstatus('Pending');

    // if (i === 2) setTabstatus('Assigned')
    // if (i === 3) setTabstatus('Picked')
    if (i === 2) setTabstatus('Delivered');
    if (i === 3) setTabstatus('Cancelled');

    // if (i === 0) setTabstatus('All orders')
    // if (i === 1) setTabstatus('Pending')
    // if (i === 1) setTabstatus('Modified')

    // if (i === 3) setTabstatus('Assigned')
    // if (i === 0) setTabstatus('Confirmed')
    //   if (i === 2) setTabstatus('Completed')
    //   if (i === 3) setTabstatus('Closed')

    console.log(i);
  };

  useEffect(() => {
    console.log(localStorage.getItem('appuserid'));

    if (localStorage.getItem('tenantid')) {
      setTenantid(localStorage.getItem('tenantid'));
      let val = localStorage.getItem('tenantid');

      fetchtable(val);
      fetchpercentage(val);
      // fetchtableactive();
      fetchtableuncovered(val);
      fetchtablecovered(val);
      fetchtablecancelled(val);
      // fetchtableassigned(val);
      // fetchtablepicked(val);
      fetchtablecreated(val);
      // fetchtableconfirmed(val);
      // fetchtablemodified(val);
      // fetchtableclosed(val)
      // fetchtable(val)
      // console.log(activeorders);
    }
  }, []);

  useEffect(() => {
    if (localStorage.getItem('tenantid')) {
      let val = localStorage.getItem('tenantid');

      // fetchtable();
      // fetchpercentage(val);
      // fetchtableactive();
      fetchtableuncovered(val);
      fetchtablecovered(val);
      fetchtablecancelled(val);
      // fetchtableassigned(val);
      // fetchtablepicked(val);
      // fetchtableconfirmed(val);
      // fetchtablemodified(val);
      // fetchtableclosed(val)
      fetchtable(val);
      fetchtablecreated(val);

      console.log(activeorders);
    }
  }, [startdate, enddate]);

  useEffect(() => {
    // if (tabstatus === 'All orders') setRows(orderarr)
    // if (tabstatus === 'Completed') setRows(orderarrcovered)
    // if (tabstatus === 'Active') setRows(orderarractive)
    // if (tabstatus === 'Pending') setRows(orderarruncovered)
    // if (tabstatus === 'Cancelled') setRows(orderarrcancelled)
    // if (tabstatus === 'Assigned') setRows(orderarrassigned)
    // if (tabstatus === 'Confirmed') setRows(orderarrconfirmed)
    if (tabstatus === 'Created') setRows(orderarrcreated);

    if (tabstatus === 'All orders') setRows(orderarr);
    if (tabstatus === 'Delivered') setRows(orderarrcovered);
    if (tabstatus === 'Pending') setRows(orderarruncovered);

    // if (tabstatus === 'Active') setRows(orderarractive)
    // if (tabstatus === 'Pending') setRows(orderarruncovered)
    if (tabstatus === 'Cancelled') setRows(orderarrcancelled);
    if (tabstatus === 'Assigned') setRows(orderarrassigned);
    //   if (tabstatus === 'Confirmed') setRows(orderarrconfirmed)
    //   if (tabstatus === 'Modified') setRows(orderarrmodified)
    //   if (tabstatus === 'Closed') setRows(orderarrclosed)
    if (tabstatus === 'Picked') setRows(orderarrpicked);
  }, [tabstatus]);

  const okclicked = () => {
    setOpen(false);
  };
  const textFieldRef = useRef(null);

  /* ============================================= || handleKeyPress (ctrl+k)| ============================================= */

  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();

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

    return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, []);

  useEffect(() => {
    var day = 60 * 60 * 24 * 1000;
    var startDate = new Date();
    if (tabstatus1 === 'Tomorrow') {
      setEnddate(new Date(startDate.getTime() + day).toISOString().substring(0, 10));
      setStartdate(new Date(startDate.getTime() + day).toISOString().substring(0, 10));
      setDateselect('select');
    } else if (tabstatus1 === 'Today') {
      setEnddate(new Date().toISOString().substring(0, 10));
      setStartdate(new Date().toISOString().substring(0, 10));
      setDateselect('select');
    } else if (tabstatus1 === 'Week') {
      setStartdate(new Date(startDate.getTime() - day * 7).toISOString().substring(0, 10));
      setEnddate(new Date().toISOString().substring(0, 10));
      setDateselect('select');
    }
    // else if (tabstatus1 === 'All') {
    //   setEnddate('');
    //   setStartdate('');

    //   setDateselect('all');
    // }
  }, [tabstatus1]);

  const choosedate = (date) => {
    setStartdate(date.$d.toISOString().substring(0, 10));
    setEnddate(date.$d.toISOString().substring(0, 10));
    setTabstatus1('');
  };
  useEffect(() => {
    if (tabstatus === 'All Orders') {
      if (searchword) {
        let arr = orderarr.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.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(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarr]);
      }
    } else if (tabstatus === 'Delivered') {
      if (searchword) {
        let arr = orderarrcovered.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.ordernotes.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrcovered]);
      }
    } else if (tabstatus === 'Active') {
      if (searchword) {
        let arr = orderarractive.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.eventname.toLowerCase().includes(searchword.toLowerCase()) ||
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            val.ordervalue.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarractive]);
      }
    } else if (tabstatus === 'Pending') {
      if (searchword) {
        let arr = orderarruncovered.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.ordernotes.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarruncovered]);
      }
    } else if (tabstatus === 'Cancelled') {
      if (searchword) {
        let arr = orderarrcancelled.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.ordernotes.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrcancelled]);
      }
    } else if (tabstatus === 'Assigned') {
      if (searchword) {
        let arr = orderarrassigned.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.ordernotes.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrassigned]);
      }
    } else if (tabstatus === 'Confirmed') {
      if (searchword) {
        let arr = orderarrconfirmed.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.ordernotes.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrconfirmed]);
      }
    } else if (tabstatus === 'Modified') {
      if (searchword) {
        let arr = orderarrmodified.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.eventname.toLowerCase().includes(searchword.toLowerCase()) ||
            val.tenantname.toLowerCase().includes(searchword.toLowerCase()) ||
            val.ordervalue.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase()) ||
            val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrmodified]);
      }
    } else if (tabstatus === 'Closed') {
      if (searchword) {
        let arr = orderarrclosed.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.eventname.toLowerCase().includes(searchword.toLowerCase()) ||
            val.tenantname.toLowerCase().includes(searchword.toLowerCase()) ||
            val.ordervalue.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase()) ||
            val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      }
    } else if (tabstatus === 'Picked') {
      if (searchword) {
        let arr = orderarrpicked.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.ordernotes.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase()) ||
            val.customername.toLowerCase().includes(searchword.toLowerCase()) ||
            val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrpicked]);
      }
    } else if (tabstatus === 'Created') {
      if (searchword) {
        let arr = orderarrcreated.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.ordernotes.toString().toLowerCase().includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrcreated]);
      }
    }
  }, [orderarr, searchword]);

  const handleChange1 = (e) => {
    setTabstatus1(e.target.innerText);
    setDatestatus(e.target.innerText);
  };

  const fetchtable = async (tid) => {
    try {
      await axios
        .get(`${process.env.REACT_APP_URL}/orders/tenant/getorders/?tenantid=${tid}`)
        .then((res) => {
          if (res.data.status) {
            let arr = [];
            res.data.details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            setArr(arr);
            console.log(res.data.Details);
            if (tabstatus == 'All Orders') {
              setRows(arr);
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtablecovered = async (tid) => {
    try {
      // await axios.get(`${process.env.REACT_APP_URL}/orders/getorders/?tenantid=${tid}&status=completed`)
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/tenant/getorders/?tenantid=${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 }];
          });
          console.log('delivered', arr);
          setArrcovered(arr);
          // }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtablecreated = async (tid) => {
    try {
      // await axios.get(`${process.env.REACT_APP_URL}/orders/getorders/?tenantid=${tid}&status=completed`)
      await axios
        .get(`${process.env.REACT_APP_URL}/orders/tenant/getorders/?tenantid=${tid}&status=created&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 }];
          });
          console.log('created', arr);
          setArrcreated(arr);
          if (tabstatus == 'Created') {
            setRows(arr);
          }
          // }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtableactive = async () => {
    try {
      await axios
        .get(
          `${process.env.REACT_APP_URL2}/orders/orderliststatus?fromdate=${startdate}&todate=${enddate}&type=${dateselect}&status=processing&sort=desc`
        )
        .then((res) => {
          if (res.data.message === 'Success') {
            let arr = [];
            res.data.Details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            setArractive(arr);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtableuncovered = async (tid) => {
    try {
      await axios
        .get(`${process.env.REACT_APP_URL}/orders/tenant/getorders/?tenantid=${tid}&status=pending&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 }];
            });
            console.log('pending', arr);
            setArruncovered(arr);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtablecancelled = async (tid) => {
    try {
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/tenant/getorders/?tenantid=${tid}&status=cancelled&fromdate=${startdate}&todate=${enddate}`
        )
        // await axios.get(`${process.env.REACT_APP_URL2}/client/orders/getordersbystatus?tenantid=${tid}&status=cancelled`)

        .then((res) => {
          // if (res.data.message === "Success") {
          let arr = [];
          console.log(res.data.details);
          res.data.details.map((val, i) => {
            arr = [...arr, { ...val, sno: i + 1 }];
          });
          console.log('cancelled', arr);
          setArrcancelled(arr);
          // }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtableassigned = async (tid) => {
    try {
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/tenant/getorders/?tenantid=${tid}&status=accepted&fromdate=${startdate}&todate=${enddate}`
        )
        .then((res) => {
          // if (res.data.message === "Success") {
          let arr = [];
          console.log(res.data.details);
          res.data.details.map((val, i) => {
            arr = [...arr, { ...val, sno: i + 1 }];
          });
          setArrassigned(arr);
          // }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtablepicked = async (tid) => {
    try {
      await axios
        .get(`${process.env.REACT_APP_URL}/orders/tenant/getorders/?tenantid=${tid}&status=picked&fromdate=${startdate}&todate=${enddate}`)
        .then((res) => {
          // if (res.data.message === "Success") {
          let arr = [];
          console.log(res.data.details);
          res.data.details.map((val, i) => {
            arr = [...arr, { ...val, sno: i + 1 }];
          });
          setArrpicked(arr);
          // }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtableconfirmed = async (tid) => {
    try {
      // await axios.get(`${process.env.REACT_APP_URL2}/orders/orderliststatus?fromdate=${startdate}&todate=${enddate}&type=${dateselect}&status=confirmed&sort=desc`)
      await axios
        .get(
          `${process.env.REACT_APP_URL2}/client/orders/getordersbystatus?tenantid=${tid}&status=confirmed&fromdate=${startdate}&todate=${enddate}`
        )

        .then((res) => {
          if (res.data.message === 'Success') {
            let arr = [];
            console.log(res.data.Details);
            res.data.Details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            setArrconfirmed(arr);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtablemodified = async (tid) => {
    try {
      // await axios.get(`${process.env.REACT_APP_URL2}/orders/orderliststatus?fromdate=${startdate}&todate=${enddate}&type=${dateselect}&status=modified&sort=desc`)
      await axios
        .get(
          `${process.env.REACT_APP_URL2}/client/orders/getordersbystatus?tenantid=${tid}&status=modified&fromdate=${startdate}&todate=${enddate}`
        )

        .then((res) => {
          if (res.data.message === 'Success') {
            let arr = [];
            console.log(res.data.Details);
            res.data.Details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            setArrmodified(arr);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtableclosed = async (tid) => {
    try {
      // await axios.get(`${process.env.REACT_APP_URL2}/orders/orderliststatus?fromdate=${startdate}&todate=${enddate}&type=${dateselect}&status=modified&sort=desc`)
      await axios
        .get(
          `${process.env.REACT_APP_URL2}/client/orders/getordersbystatus?tenantid=${tid}&status=closed&fromdate=${startdate}&todate=${enddate}`
        )
        .then((res) => {
          if (res.data.message === 'Success') {
            let arr = [];
            console.log(res.data.Details);
            res.data.Details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            setArrclosed(arr);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  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/?applocationid=${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.created / 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);
    }
  };

  return (
    <>
      {loading && <Loader />}
      <Grid container rowSpacing={4.5} columnSpacing={2.75}>
        <Grid item xs={12} sx={{ mb: -2.25 }}>
          <Stack direction={{ xs: 'column', md: 'row' }} justifyContent="space-between" alignItems="center" spacing={2}>
            <Stack direction="column" alignItems="flex-start" spacing={1}>
              <Typography variant="h3">Orders</Typography>
            </Stack>
          </Stack>
        </Grid>

        <Grid item xs={12} lg={3} sm={6}>
          <HoverSocialCard
            primary="Created Orders"
            secondary={created === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : created}
            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={{ mb: -3 }}>
          <Stack direction={'row'} justifyContent={'space-between'}>
            {startdate && enddate && (
              <Stack direction="row" spacing={2}>
                <Chip label={`Orders-${datestatus ? datestatus : ''}`} color="primary" variant="light" size="small" />
                <Chip
                  label={
                    <Typography noWrap color="secondary">
                      {dayjs(startdate).format('DD/MM/YYYY')} - {dayjs(enddate).format('DD/MM/YYYY')}
                    </Typography>
                  }
                  variant="combined"
                  color="warning"
                  size="small"
                />
              </Stack>
            )}
            {(!startdate || !enddate) && (
              <>
                <Stack direction="row" spacing={2}>
                  <Chip label="Orders-All" color="primary" variant="light" size="small" />
                </Stack>
              </>
            )}

            <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>
          </Stack>
        </Grid>

        <Grid item xs={12}>
          <Box sx={{ overflow: 'auto', border: 1, borderColor: 'grey.200', borderRadius: 2, backgroundColor: '#fff', minHeight: 350 }}>
            <Stack
              alignItems="center"
              justifyContent="space-between"
              direction="row"
              sx={{
                p: 2,
                width: '100%'
              }}
            >
              <Tabs value={tabvalue} onChange={handleChangetab} variant="scrollable" scrollButtons="auto">
                {/* <Tab label="All orders"
                  iconPosition="end"
                  icon={<Chip label={allorders} color="primary" variant="light" size="small" />}
                /> */}
                <Tab
                  label="Created"
                  icon={<Chip label={orderarrcreated.length} color="primary" variant="light" size="small" />}
                  iconPosition="end"
                />
                <Tab
                  label="Pending"
                  icon={<Chip label={orderarruncovered.length} color="primary" variant="light" size="small" />}
                  iconPosition="end"
                />
                {/* <Tab label="Accepted"
                icon={<Chip label={assigned} color="primary" variant="light" size="small" />}
                iconPosition="end"
              /> */}
                {/* <Tab label="Confirmed"
                  icon={<Chip label={confirmed} color="primary" variant="light" size="small" />}
                  iconPosition="end"
                /> */}
                {/* <Tab label="Modified"
                  icon={<Chip label={modified} color="primary" variant="light" size="small" />}
                  iconPosition="end"
                /> */}
                {/* <Tab label="Picked"
                icon={<Chip label={picked} color="primary" variant="light" size="small" />}
                iconPosition="end"
              /> */}

                <Tab
                  label="Delivered"
                  icon={<Chip label={orderarrcovered.length} color="primary" variant="light" size="small" />}
                  iconPosition="end"
                />

                {/* <Tab label="Closed"
                  icon={<Chip label={closed} color="primary" variant="light" size="small" />}
                  iconPosition="end"
                /> */}
                <Tab
                  label="Cancelled"
                  icon={<Chip label={orderarrcancelled.length} color="primary" variant="light" size="small" />}
                  iconPosition="end"
                />
              </Tabs>

              <FormControl sx={{ width: 250, display: { xs: 'none', md: 'flex' } }}>
                <OutlinedInput
                  inputRef={textFieldRef}
                  size="small"
                  id="header-search"
                  aria-describedby="header-search-text"
                  inputProps={{
                    'aria-label': 'weight'
                  }}
                  placeholder="Search (ctrl+k)"
                  value={searchword}
                  onChange={(e) => {
                    setSearchword(e.target.value);
                  }}
                  autoComplete="off"
                  startAdornment={
                    <InputAdornment position="start" sx={{ mr: -0.5 }}>
                      <SearchOutlined style={{ color: theme.palette.primary.main }} />
                    </InputAdornment>
                  }
                  endAdornment={
                    <Tooltip title="clear">
                      <IconButton
                        sx={{ visibility: searchword ? 'visible' : 'hidden' }}
                        onClick={() => {
                          setSearchword('');
                        }}
                      >
                        <ClearIcon fontSize="small" sx={{ color: theme.palette.primary.main }} />
                      </IconButton>
                    </Tooltip>
                  }
                />
              </FormControl>
            </Stack>

            <Box sx={{ width: '100%', display: 'table', tableLayout: 'fixed' }}>
              <EnhancedTable />
            </Box>
          </Box>
        </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('');
                  }
                }
                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}>
              ok
            </Button>
          </Stack>
        </Dialog>
      </Grid>
    </>
  );
};

export default Orders;
