import { React, useState, useEffect, useRef, Fragment } from 'react';

import axios from 'axios';
import { useQuery } from '@tanstack/react-query';
import { Empty } from 'antd';
import TaskAltIcon from '@mui/icons-material/TaskAlt';
import MyLocationIcon from '@mui/icons-material/MyLocation';
import HighlightOffIcon from '@mui/icons-material/HighlightOff';
import { enqueueSnackbar } from 'notistack';
import { CalendarMonth } from '@mui/icons-material';

// material-ui
import {
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Dialog,
  DialogTitle,
  Typography,
  DialogContent,
  Stack,
  Button,
  IconButton,
  Tooltip,
  Chip,
  Autocomplete,
  TextField,
  FormControl,
  OutlinedInput,
  InputAdornment,
  Collapse,
  Badge
} from '@mui/material';
import ClearIcon from '@mui/icons-material/Clear';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import { SearchOutlined } from '@ant-design/icons';
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 { FilterList } from '@mui/icons-material';

// project imports

import MainCard from 'components/MainCard';
import Loader from 'components/Loader';
import { useTheme } from '@mui/material/styles';
import TitleCard from '../titleCard';
import { getreportlocationsummary, gettenantlocations } from '../api/api';
import CircularLoader from 'components/nearle_components/CircularLoader';
import { getValueColor } from 'components/nearle_components/getValueColor';

function formatNumberToRupees(value) {
  return new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR',
    minimumFractionDigits: 2
  }).format(value);
}

const opentoast = (message, variant, time) => {
  enqueueSnackbar(message, {
    variant: variant,
    anchorOrigin: { vertical: 'top', horizontal: 'right' },
    autoHideDuration: time ? time : 1500
  });
};

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

export default function OrdersReport() {
  // const [rows, setRows] = useState([]);
  const theme = useTheme();
  const bgcolor0 = theme.palette.primary.lighter;
  const bgcolor1 = '#ffcdd2';
  const bgcolor2 = '#f8bbd0';
  const tenantid = localStorage.getItem('tenantid');
  const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
  const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));
  const [open, setOpen] = useState(false);
  const [openRow, setOpenRow] = useState(null); // Initially no row is open
  const [datestatus, setDatestatus] = useState('Today');
  const [total, settotal] = useState(0);
  const [totalOrders, settotalOrders] = useState(0);
  const [totalOrderPend, setTotalOrderPend] = useState(0);
  const [totalOrderComplete, setTotalOrderComplete] = useState(0);
  const [totalOrderCancel, setTotalOrderCancel] = useState(0);
  const [totalDeliPend, setTotalDeliPend] = useState(0);
  const [totalDeliComplete, setTotalDeliComplete] = useState(0);
  const [totalDeliCancel, setTotalDeliCancel] = useState(0);
  const [searchword, setSearchword] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const textFieldRef = useRef(null);
  const [ridersdata, setRidersdata] = useState(null);
  const [selectedLocation, setSelectedLocation] = useState(null);
  const [locationId, setLocationId] = useState(0);
  const [searchLocation, setSearchLocation] = useState('');

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedSearch(searchword);
    }, 400);

    return () => clearTimeout(handler);
  }, [searchword]);
  useEffect(() => {
    console.log('openRow', openRow);
  }, [openRow]);

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

  // ============================================= || gettenantlocations (branches) || =============================================

  const {
    data: tenantLocations,
    isLoading: tenantLocationsIsLoading,
    isError: tenantLocationsIsError,
    error: tenantLocationsError
  } = useQuery({
    queryKey: ['tenantlocations', searchLocation],
    queryFn: gettenantlocations
  });

  // ==============================|| fetchOrdersSummary (orders summary)||============================== //
  const {
    isLoading: isLoadingReports,
    isError: isErrorReports, //true or false
    data: rows,
    error: reportsError
  } = useQuery({
    queryKey: [startdate, enddate, locationId, debouncedSearch],
    queryFn: getreportlocationsummary
  });
  // ==============================|| getriderlocationsummary by tenid (orders summary)||============================== //
  const getriderlocationsummary = async (id) => {
    try {
      const riderRes = await axios.get(
        `${process.env.REACT_APP_URL}/deliveries/getriderlocationsummary/?&tenantid=${tenantid}&locationid=${id}&fromdate=${startdate}&todate=${enddate}`
      );
      console.log('riderRes', riderRes.data.details);
      setRidersdata(riderRes.data.details);
    } catch (error) {
      console.log('riderRes', error);
    }
  };

  // ==============================|| calculate||============================== //
  const calculate = () => {
    let calculatedTotal = 0;
    let ordersTotal = 0;
    let Orderpending = 0;
    let OrderComplete = 0;
    let OrderCancel = 0;
    let deliverypending = 0;
    let deliverycomplete = 0;
    let deliverycancel = 0;
    rows &&
      rows.forEach((row) => {
        calculatedTotal += row.charges;
        ordersTotal += row.totalorders;
        Orderpending += row.Orderspending;
        OrderComplete += row.orderscompleted;
        OrderCancel += row.orderscancelled;
        deliverypending += row.deliveriespending;
        deliverycomplete += row.deliveriescompleted;
        deliverycancel += row.deliveriescancelled;
      });
    // Update the state after the calculation is done
    settotal(calculatedTotal);
    settotalOrders(ordersTotal);
    setTotalOrderPend(Orderpending);
    setTotalOrderComplete(OrderComplete);
    setTotalOrderCancel(OrderCancel);
    setTotalDeliPend(deliverypending);
    setTotalDeliComplete(deliverycomplete);
    setTotalDeliCancel(deliverycancel);
  };
  useEffect(() => {
    calculate();
  }, [rows]);

  let errormessage = '';

  if (isErrorReports && reportsError?.message) {
    errormessage = `An error has occurred: (isErrorReports) ${reportsError.message}`;
  } else if (tenantLocationsIsError && tenantLocationsError?.message) {
    errormessage = `An error has occurred: (tenantLocationsIsError) ${tenantLocationsError.message}`;
  }

  useEffect(() => {
    if (errormessage) {
      console.log('errormessage', errormessage);
      opentoast(errormessage, 'warning', 2000);
    }
  }, [errormessage]);

  return (
    <>
      {(isLoadingReports || tenantLocationsIsLoading) && <Loader />}
      {(isLoadingReports || tenantLocationsIsLoading) && <CircularLoader />}
      <TitleCard
        title="Orders Summary"
        secondary={
          <Stack>
            {startdate && enddate && (
              <Stack direction="row" spacing={2} flexWrap={'wrap'} gap={1}>
                <Badge badgeContent={rows?.length || 0} color="primary">
                  <Chip label={`Location-${datestatus}`} color="primary" variant="light" size="small" />
                </Badge>
                <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"
                  deleteIcon={<CalendarMonth style={{ fontSize: 18 }} />}
                  onDelete={() => {
                    setOpen(true);
                  }}
                  onClick={() => setOpen(true)}
                  sx={{ cursor: 'pointer' }}
                />
              </Stack>
            )}
            {(!startdate || !enddate) && (
              <>
                <Stack direction="row" spacing={2}>
                  <Chip label="Orders-All" color="primary" variant="light" size="small" />
                </Stack>
              </>
            )}
          </Stack>
        }
      />{' '}
      <MainCard
        content={false}
        title={
          <Stack
            direction="row"
            gap={2}
            flexWrap="wrap"
            sx={{
              alignItems: 'center',
              width: '100%',
              justifyContent: 'flex-end'
            }}
          >
            {/* Search Input */}
            <FormControl sx={{ minWidth: 250, maxWidth: 400, flex: 1 }}>
              <OutlinedInput
                inputRef={textFieldRef}
                id="header-search"
                placeholder="Search (Ctrl + K)"
                value={searchword}
                onChange={(e) => setSearchword(e.target.value)}
                autoComplete="off"
                size="medium"
                sx={{
                  bgcolor: 'white',
                  borderRadius: 2
                }}
                startAdornment={
                  <InputAdornment position="start">
                    <SearchOutlined />
                  </InputAdornment>
                }
                endAdornment={
                  <InputAdornment position="end">
                    <IconButton sx={{ visibility: searchword ? 'visible' : 'hidden' }} onClick={() => setSearchword('')}>
                      <ClearIcon sx={{ fontSize: 20, color: '#65387A' }} />
                    </IconButton>
                  </InputAdornment>
                }
              />
            </FormControl>

            {/* Location Input */}
            {tenantLocations?.length === 1 ? (
              <TextField
                variant="outlined"
                label="Business Location"
                value={tenantLocations[0]?.locationname}
                fullWidth
                focused
                sx={{
                  minWidth: 250,
                  maxWidth: 400,
                  flex: 1,
                  borderRadius: 2
                }}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <MyLocationIcon color="primary" />
                    </InputAdornment>
                  ),
                  sx: { bgcolor: 'white' }
                }}
              />
            ) : (
              <Autocomplete
                fullWidth
                options={tenantLocations || []}
                value={selectedLocation}
                getOptionLabel={(o) => `${o.locationname} (${o.suburb})`}
                onChange={(event, value, reason) => {
                  setSelectedLocation(value);
                  setLocationId(value ? value.locationid : 0);
                }}
                sx={{
                  minWidth: 250,
                  maxWidth: 400,
                  flex: 1
                }}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    label="Choose Location"
                    color="primary"
                    sx={{
                      bgcolor: 'white',
                      borderRadius: 2
                    }}
                  />
                )}
              />
            )}
          </Stack>
        }
      >
        <TableContainer
          sx={{
            overflow: 'auto',
            '&::-webkit-scrollbar': {
              width: '12px', // Width of vertical scrollbar
              height: '14px', // Height of horizontal scrollbar,
              borderRadius: 10
            },
            '&::-webkit-scrollbar-thumb': {
              backgroundColor: '#65387A' // Color of the scrollbar thumb
            }
          }}
        >
          <Table>
            <TableHead>
              <TableRow sx={{ bgcolor: bgcolor0 }}>
                <TableCell rowSpan={2}># </TableCell>
                <TableCell rowSpan={2}> Location</TableCell>
                <TableCell rowSpan={2}>All </TableCell>
                <TableCell colSpan={3} sx={{ textAlign: 'center', bgcolor: bgcolor1 }}>
                  Orders{' '}
                </TableCell>
                <TableCell colSpan={3} sx={{ textAlign: 'center', bgcolor: bgcolor2 }}>
                  Deliveries{' '}
                </TableCell>
                <TableCell rowSpan={2}> Kilometer</TableCell>
                {/* <TableCell rowSpan={2}>Charges </TableCell> */}
                <TableCell rowSpan={2}>Amount </TableCell>
                <TableCell rowSpan={2}> Action</TableCell>
              </TableRow>
              {/* sx={{ bgcolor: headCell.bgcolor }} */}
              <TableRow>
                <TableCell sx={{ bgcolor: bgcolor1 }}>Pending</TableCell>
                <TableCell sx={{ bgcolor: bgcolor1 }}>Completed</TableCell>
                <TableCell sx={{ bgcolor: bgcolor1 }}>Cancelled</TableCell>
                <TableCell sx={{ bgcolor: bgcolor2 }}>Pending</TableCell>
                <TableCell sx={{ bgcolor: bgcolor2 }}>Completed</TableCell>
                <TableCell sx={{ bgcolor: bgcolor2 }}>Cancelled</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {rows?.length !== 0 ? (
                rows?.map((row, index) => (
                  <>
                    {/* ============================================ || tablerow 1 || ============================================ */}

                    <TableRow
                      key={row.locationid}
                      sx={{
                        cursor: openRow === row.locationid ? 'pointer' : null
                      }}
                    >
                      <TableCell scope="row" padding="none">
                        {index + 1}
                      </TableCell>
                      <TableCell align="left">
                        <Stack sx={{ ml: -2 }}>
                          <Typography> {row.locationname}</Typography>
                          <Typography variant="body2">Id : {row.locationid}</Typography>
                        </Stack>
                      </TableCell>
                      <TableCell align="center" sx={{ color: getValueColor(row.totalorders) }}>
                        {row.totalorders}
                      </TableCell>
                      <TableCell align="center" sx={{ color: getValueColor(row.Orderspending) }}>
                        {row.Orderspending}
                      </TableCell>
                      <TableCell align="center" sx={{ color: getValueColor(row.orderscompleted) }}>
                        {row.orderscompleted}
                      </TableCell>
                      <TableCell align="center" sx={{ color: getValueColor(row.orderscancelled) }}>
                        {row.orderscancelled}
                      </TableCell>
                      <TableCell align="center" sx={{ color: getValueColor(row.deliveriespending) }}>
                        {' '}
                        {row.deliveriespending}
                      </TableCell>
                      <TableCell align="center" sx={{ color: getValueColor(row.deliveriescompleted) }}>
                        {' '}
                        {row.deliveriescompleted}
                      </TableCell>
                      <TableCell align="center" sx={{ color: getValueColor(row.deliveriescancelled) }}>
                        {' '}
                        {row.deliveriescancelled}
                      </TableCell>
                      <TableCell align="left">
                        <Tooltip title="Cumulative Kms" placement="top">
                          <Chip
                            size="small"
                            label={parseFloat(row.cumulativekms).toFixed(2)}
                            sx={{
                              color: '#f44336',
                              bgcolor: '#ffcdd2',
                              border: '1px solid #f44336',
                              mb: 1,
                              cursor: 'pointer',
                              minWidth: 80
                            }}
                          />
                        </Tooltip>

                        {/* <br />
                        <Tooltip title="Actual kms" placement="bottom">
                          <Chip
                            size="small"
                            label={parseFloat(row.actualkms).toFixed(2)}
                            sx={{
                              color: '#43a047',
                              bgcolor: '#c8e6c9',
                              border: '1px solid #43a047',
                              cursor: 'pointer',
                              minWidth: 80
                            }}
                          />
                        </Tooltip> */}
                      </TableCell>
                      {/* <TableCell align="left"> */}
                      {/* <Tooltip title="Pay on Delivery" placement="top">
                          <Chip
                            size="small"
                            label={formatNumberToRupees(row.payondelivery)}
                            variant="outlined"
                            color="error"
                            sx={{
                              color: '#f44336',
                              bgcolor: '#ffcdd2',
                              border: '1px solid #f44336',
                              mb: 1,
                              cursor: 'pointer',
                              minWidth: 80
                            }}
                          />
                        </Tooltip>
                        <br /> */}
                      {/* <Tooltip title="Pay Later" placement="bottom">
                          <Chip
                            size="small"
                            label={formatNumberToRupees(row.paylater)}
                            variant="outlined"
                            color="success"
                            sx={{
                              color: '#43a047',
                              bgcolor: '#c8e6c9',
                              border: '1px solid #43a047',
                              cursor: 'pointer',
                              minWidth: 80
                            }}
                          />
                        </Tooltip> */}
                      {/* </TableCell> */}
                      <TableCell align="right">
                        <Tooltip title="Total Charges" placement="top">
                          <Chip
                            size="small"
                            label={formatNumberToRupees(row.charges)}
                            sx={{
                              color: 'primary.main',
                              bgcolor: '#e1bee7',
                              border: '1px solid #662582 ',
                              cursor: 'pointer',
                              minWidth: 100
                            }}
                          />
                        </Tooltip>
                      </TableCell>
                      <TableCell align="center">
                        <IconButton
                          aria-label="expand row"
                          size="small"
                          onClick={() => {
                            getriderlocationsummary(row.locationid);
                            setOpenRow(openRow === row.locationid ? null : row.locationid);
                          }}
                          sx={{
                            bgcolor: openRow === row.locationid ? 'primary.main' : null,
                            color: openRow === row.locationid ? 'white' : null,
                            '&:hover': {
                              bgcolor: openRow === row.locationid ? 'primary.main' : '#e1bee7'
                            }
                          }}
                        >
                          {openRow === row.locationid ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
                        </IconButton>
                      </TableCell>
                    </TableRow>
                    {/* ============================================ || collapsive row || ============================================ */}
                    {openRow === row.locationid && (
                      <TableRow
                        sx={{
                          bgcolor: 'white',
                          '&:hover': {
                            bgcolor: 'white!important'
                          },
                          cursor: openRow === row.locationid ? 'pointer' : null
                        }}
                      >
                        <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={15}>
                          <Collapse in={openRow === row.locationid} timeout="auto" unmountOnExit>
                            <Box sx={{ margin: 1 }}>
                              <Table size="small" aria-label="purchases">
                                <TableHead
                                  sx={{
                                    bgcolor: 'white',
                                    '&:onhover': {
                                      bgcolor: 'white !important'
                                    }
                                  }}
                                >
                                  <TableRow
                                    sx={{
                                      bgcolor: openRow === row.locationid ? theme.palette.secondary.lighter : null
                                    }}
                                  >
                                    <TableCell align="center">#</TableCell>
                                    <TableCell>Rider</TableCell>
                                    <TableCell align="center">Deliveries</TableCell>
                                    <TableCell align="center">Pending</TableCell>
                                    <TableCell align="center">Assigned</TableCell>
                                    <TableCell align="center">Accepted</TableCell>
                                    <TableCell align="center">Arrived</TableCell>
                                    <TableCell align="center">Picked</TableCell>
                                    <TableCell align="center">Skipped</TableCell>
                                    <TableCell align="center">Delivered</TableCell>
                                    <TableCell align="center">kms</TableCell>
                                    {/* <TableCell align="center">POD/PLA</TableCell> */}
                                    <TableCell align="center">Charges</TableCell>
                                  </TableRow>
                                </TableHead>
                                <TableBody
                                  sx={{
                                    bgcolor: 'white',
                                    '&:onhover': {
                                      bgcolor: 'white !important'
                                    }
                                  }}
                                >
                                  {ridersdata?.map((rider, index) => (
                                    <TableRow
                                      key={rider?.tenantname}
                                      // sx={{
                                      //   bgcolor: openRow === row.locationid ? '#f3e5f5' : null,
                                      //   '&:hover': {
                                      //     bgcolor: openRow === row.locationid ? '#f3e5f5!important' : null
                                      //   }
                                      // }}
                                    >
                                      <TableCell align="center" padding="none">
                                        {index + 1}
                                      </TableCell>
                                      <TableCell align="left">
                                        <Stack direction="row" sx={{ ml: -2 }}>
                                          {rider?.firstname}
                                          {rider?.status == 'Active' ? (
                                            <TaskAltIcon fontSize="small" color="success" sx={{ ml: 1 }} />
                                          ) : (
                                            <HighlightOffIcon fontSize="small" color="error" sx={{ ml: 1 }} />
                                          )}
                                        </Stack>
                                      </TableCell>
                                      <TableCell align="center" sx={{ color: getValueColor(rider.totalorders) }}>
                                        {rider?.totalorders}
                                      </TableCell>
                                      <TableCell align="center" sx={{ color: getValueColor(rider.pending) }}>
                                        {rider?.pending}
                                      </TableCell>
                                      <TableCell align="center" sx={{ color: getValueColor(rider.assigned) }}>
                                        {rider?.assigned}
                                      </TableCell>
                                      <TableCell align="center" sx={{ color: getValueColor(rider.accepted) }}>
                                        {rider?.accepted}
                                      </TableCell>
                                      <TableCell align="center" sx={{ color: getValueColor(rider.picked) }}>
                                        {rider?.picked}
                                      </TableCell>
                                      <TableCell align="center" sx={{ color: getValueColor(rider.arrived) }}>
                                        {rider?.arrived}
                                      </TableCell>
                                      <TableCell align="center" sx={{ color: getValueColor(rider.skipped) }}>
                                        {rider?.skipped}
                                      </TableCell>
                                      <TableCell align="center" sx={{ color: getValueColor(rider.delivered) }}>
                                        {rider?.delivered}
                                      </TableCell>
                                      <TableCell align="center">
                                        {/* <Tooltip title="kms" placement="top"> */}
                                        <Chip
                                          size="small"
                                          label={rider?.cumulativekms}
                                          sx={{
                                            color: '#1976d2',
                                            bgcolor: '#e3f2fd',
                                            mr: 1,
                                            border: '1px solid #1976d2',
                                            cursor: 'pointer',
                                            minWidth: 80
                                          }}
                                        />
                                        {/* </Tooltip> */}
                                        {/* <Tooltip title="Actual kms" placement="top">
                                          <Chip
                                            size="small"
                                            label={rider?.actualkms}
                                            sx={{
                                              color: '#ff8f00',
                                              bgcolor: '#ffecb3',
                                              border: '1px solid #ff8f00',
                                              cursor: 'pointer',
                                              minWidth: 80
                                            }}
                                          />
                                        </Tooltip> */}
                                      </TableCell>

                                      {/* <TableCell align="center"> */}
                                      {/* <Tooltip title="Pay on Delivery" placement="top">
                                          <Chip
                                            size="small"
                                            label={formatNumberToRupees(rider?.payondelivery)}
                                            sx={{
                                              color: '#f44336',
                                              bgcolor: '#ffcdd2',
                                              border: '1px solid #f44336',
                                              mr: 1,
                                              cursor: 'pointer',
                                              minWidth: 80
                                            }}
                                          />
                                        </Tooltip> */}
                                      {/* <Tooltip title="Paylater" placement="top"> */}
                                      {/* <Chip
                                          size="small"
                                          label={formatNumberToRupees(rider?.Paylater)}
                                          sx={{
                                            color: '#43a047',
                                            bgcolor: '#c8e6c9',
                                            border: '1px solid #43a047',
                                            cursor: 'pointer',
                                            minWidth: 80
                                          }}
                                        /> */}
                                      {/* </Tooltip> */}
                                      {/* </TableCell> */}
                                      <TableCell align="center">
                                        <Tooltip title="Amount" placement="top">
                                          <Chip
                                            size="small"
                                            label={formatNumberToRupees(rider?.deliveryamt)}
                                            sx={{
                                              color: 'primary.main',
                                              bgcolor: '#e1bee7',
                                              border: '1px solid #662582 ',
                                              cursor: 'pointer',
                                              minWidth: 100
                                            }}
                                          />
                                        </Tooltip>
                                      </TableCell>
                                    </TableRow>
                                  ))}
                                </TableBody>
                              </Table>
                            </Box>
                          </Collapse>
                        </TableCell>
                      </TableRow>
                    )}
                  </>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={17} rowSpan={40}>
                    <Stack width={'100%'} direction={'row'} justifyContent={'center'}>
                      <Empty />
                    </Stack>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
            {/* ============================================ || total - row || ============================================ */}
            <TableRow sx={{ bgcolor: '#e0e0e0' }}>
              <TableCell colSpan={2}>
                <Typography variant="h5">Total</Typography>
              </TableCell>
              <TableCell align="center">
                <Typography variant="h5">{totalOrders}</Typography>{' '}
              </TableCell>
              <TableCell align="center">
                <Typography variant="h5">{totalOrderPend}</Typography>{' '}
              </TableCell>
              <TableCell align="center">
                <Typography variant="h5">{totalOrderComplete}</Typography>{' '}
              </TableCell>
              <TableCell align="center">
                <Typography variant="h5"> {totalOrderCancel}</Typography>
              </TableCell>
              <TableCell align="center">
                <Typography variant="h5">{totalDeliPend}</Typography>{' '}
              </TableCell>
              <TableCell align="center">
                <Typography variant="h5">{totalDeliComplete}</Typography>{' '}
              </TableCell>
              <TableCell align="center">
                <Typography variant="h5"> {totalDeliCancel}</Typography>
              </TableCell>
              <TableCell></TableCell>
              <TableCell align="right" sx={{ pr: -2 }}>
                <Typography variant="h5">{formatNumberToRupees(total)}</Typography>
              </TableCell>{' '}
              <TableCell></TableCell>
            </TableRow>
          </Table>
        </TableContainer>
      </MainCard>
      {/* ============================================ || date filter dialog || ============================================ */}
      <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') {
                setStartdate('');
                setEnddate('');

                setOpen(false);
              } else {
                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={() => setOpen(false)}>
            ok
          </Button>
        </Stack>
      </Dialog>
    </>
  );
}
