import { React, useState, useEffect, useRef } from 'react';
import TitleCard from 'pages/nearle/titleCard';
import axios from 'axios';
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import { Empty } from 'antd';
import ClearIcon from '@mui/icons-material/Clear';
import { useTheme } from '@mui/material/styles';
import { SlLocationPin } from 'react-icons/sl';
import MapWithRoute from './mapWithRoute';
import { enqueueSnackbar } from 'notistack';
import MyLocationIcon from '@mui/icons-material/MyLocation';

// material-ui
import {
  Divider,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Dialog,
  DialogTitle,
  Typography,
  DialogContent,
  Stack,
  Button,
  IconButton,
  Tooltip,
  Chip,
  FormControl,
  OutlinedInput,
  InputAdornment,
  Badge,
  Autocomplete,
  TextField,
  CircularProgress,
  Box
} from '@mui/material';
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 { CalendarMonth, FilterList } from '@mui/icons-material';

// project imports
import { fetchDeliverySummary, fetchorderdetails } from '../api/api';
import MainCard from 'components/MainCard';
import { CSVExport } from 'components/third-party/ReactTable';
import Loader from 'components/Loader';
import { useDebounce } from 'components/nearle_components/useDebounce';

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

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

export default function OrdersDetails() {
  const tenId = localStorage.getItem('tenantid');
  const textFieldRef = useRef(null);
  const loadMoreRef = useRef();
  const containerRef = useRef();
  const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
  const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));
  const [open, setOpen] = useState(false);
  const [datestatus, setDatestatus] = useState('Today');
  const [totalCharge, settotalCharge] = useState(0);
  const [totalAmount, settotalAmount] = useState(0);
  const [searchword, setSearchword] = useState('');
  const theme = useTheme();
  const [riderCoordinates, setRiderCoordinates] = useState([]);
  const [riderStart, setRiderStart] = useState();
  const [riderEnd, setRiderEnd] = useState();
  const [mapOpen, setMapOpen] = useState(false);
  const [mapTenant, setMapTenant] = useState({});
  const [currentStatus, setCurrentStatus] = useState('All');
  const [statusCount, setStatusCount] = useState(0);
  const [tenantLocations, setTenantlocations] = useState([]);
  const [locationId, setLocationId] = useState(0);
  const [locoName, setLocoName] = useState('Select Location');

  const debouncedSearch = useDebounce(searchword, 500);
  const status = [
    { id: 0, status: 'All', statusLow: 'All' },
    { id: 1, status: 'Pending', statusLow: 'pending' },
    { id: 2, status: 'Accepted', statusLow: 'accepted' },
    { id: 3, status: 'Arrived', statusLow: 'arrived' },
    { id: 4, status: 'Picked', statusLow: 'picked' },
    { id: 5, status: 'Active', statusLow: 'active' },
    { id: 6, status: 'Delivered', statusLow: 'delivered' },
    { id: 7, status: 'Skipped', statusLow: 'skipped' },
    { id: 8, status: 'Cancelled', statusLow: 'cancelled' }
  ];

  // ============================================= || gettenantlocations (branches) || =============================================
  const gettenantlocations = async (id) => {
    try {
      const res = await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenantlocations/?tenantid=${id}`);
      console.log('gettenantlocations', res.data.details);
      if (res.data.details.length == 1) {
        setIsLocation(true);
        setTenantlocations(res.data.details);
        setPickCust(res.data.details[0]);
      } else {
        setTenantlocations(res.data.details);
      }
    } catch (err) {
      console.log('gettenantlocations', err);
    }
  };
  useEffect(() => {
    gettenantlocations(tenId);
  }, []);
  const getdeliverylogs = async (id) => {
    console.log('deliveryid', id);
    try {
      const res = await axios.get(`${process.env.REACT_APP_URL}/deliveries/getdeliverylogs/?deliveryid=${id}`);
      console.log('getdeliverylogs', res.data.details);
      const datas = res.data.details;
      if (datas.length != 0) {
        setRiderStart(datas[0].logdate);
        setRiderEnd(datas[datas.length - 1].logdate);
        const coData = datas.map((data) => ({ lat: data.latitude, lng: data.longitude }));
        console.log('coData', coData);
        setRiderCoordinates(coData);
      } else {
        opentoast('No Logs Found ', 'error', 2000);
      }
    } catch (error) {
      console.log('getdeliverylogs', error);
    }
  };

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

  // ==============================|| textFieldRef  (cmd+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);
    };
  }, []);

  // ==============================|| fetchorderdetails (orders)||============================== //

  const {
    data: rowdata,
    isError: isErrorOrderDetails,
    error: orderDetailsError,
    fetchNextPage,
    isLoading: isLoadingOrderDetails,
    hasNextPage,
    isFetchingNextPage
    // status: rowdataStatus
  } = useInfiniteQuery({
    queryKey: [startdate, enddate, currentStatus, locationId, debouncedSearch],
    queryFn: fetchorderdetails,
    getNextPageParam: (lastPage) => lastPage.nextPage
  });

  const rows = rowdata?.pages.flatMap((page) => page.details) || [];

  useEffect(() => {
    if (!hasNextPage) return;
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          fetchNextPage();
        }
      },
      {
        root: document.querySelector('.MuiTableContainer-root'), // 👈 or explicitly TableContainer
        rootMargin: '0px',
        threshold: 1.0
      }
    );
    if (loadMoreRef.current) observer.observe(loadMoreRef.current);
    return () => {
      if (loadMoreRef.current) observer.unobserve(loadMoreRef.current);
    };
  }, [hasNextPage, fetchNextPage]);

  // ==================================== || fetchDeliverySummary || ====================================

  const { data: deliverycount } = useQuery({
    queryKey: ['deliverycount', startdate, enddate, currentStatus, locationId],
    queryFn: fetchDeliverySummary
  });

  useEffect(() => {
    console.log('currentStatus', currentStatus);

    currentStatus == 'All'
      ? setStatusCount(deliverycount?.total)
      : currentStatus == 'pending'
      ? setStatusCount(deliverycount?.pending)
      : currentStatus == 'accepted'
      ? setStatusCount(deliverycount?.accepted)
      : currentStatus == 'arrived'
      ? setStatusCount(deliverycount?.arrived)
      : currentStatus == 'picked'
      ? setStatusCount(deliverycount?.picked)
      : currentStatus == 'active'
      ? setStatusCount(deliverycount?.active)
      : currentStatus == 'delivered'
      ? setStatusCount(deliverycount?.delivered)
      : currentStatus == 'cancelled'
      ? setStatusCount(deliverycount?.cancelled)
      : setStatusCount(0);
  }, [currentStatus, deliverycount]);

  // ==============================|| calculate||============================== //

  const calculate = () => {
    let calculatedTotalCharge = 0;
    let calculatedTotalAmount = 0;
    rows &&
      rows.forEach((row) => {
        calculatedTotalCharge += row.deliverycharges;
      });
    settotalCharge(calculatedTotalCharge);
    rows &&
      rows.forEach((row) => {
        calculatedTotalAmount += row.deliveryamt;
      });
    console.log('calculatedTotalAmount', calculatedTotalAmount);
    settotalAmount(calculatedTotalAmount);
  };
  useEffect(() => {
    calculate();
  }, [rows]);

  // ==============================|| fetchAppLocations ||============================== //

  if (isErrorOrderDetails) return 'An error has occurred:(isErrorOrderDetails) ' + orderDetailsError.message;

  // to download ex format filtered data

  const csvData = rows.map((order) => ({
    tenantname: order.tenantname,
    tenantcity: order.tenantcity,
    tenantcontactno: order.tenantcontactno,
    rider: order.rider,
    orderid: order.orderid,
    orderdate: order.orderdate,
    deliverydate: order.deliverydate,
    orderstatus: order.orderstatus,
    deliverystatus: order.deliverystatus,
    ordernotes: order.ordernotes,
    kms: order.kms,
    actualkms: order.actualkms,
    assigntime: order.assigntime,
    starttime: order.starttime,
    arrivaltime: order.arrivaltime,
    pickuptime: order.pickuptime,
    deliverytime: order.deliverytime,
    canceltime: order.canceltime,
    deliverycharge: order.deliverycharge,
    deliveryamt: order.deliveryamt,
    pickupcustomer: order.pickupcustomer,
    pickupcontactno: order.pickupcontactno,
    pickupaddress: order.pickupaddress,
    pickupsuburb: order.pickupsuburb,
    pickupcity: order.pickupcity,
    pickuplat: order.pickuplat,
    pickuplong: order.pickuplong,
    deliverycustomer: order.deliverycustomer,
    deliverycontactno: order.deliverycontactno,
    deliveryaddress: order.deliveryaddress,
    deliverysuburb: order.deliverysuburb,
    deliverylat: order.deliverylat,
    deliverylong: order.deliverylong,
    locationname: order.locationname,
    locationsuburb: order.locationsuburb,
    locationcity: order.locationcity,
    locationcontactno: order.locationcontactno
  }));

  function formatDate(dateString) {
    const date = dayjs(dateString);
    const formattedDate = date.format('DD/MM/YYYY ');
    return formattedDate;
  }
  function formatTime(dateString) {
    const date = dayjs(dateString);
    const formattedDate = date.format(' hh:mm A');
    return formattedDate;
  }
  const handleScroll = (event) => {
    const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
    if (scrollTop + clientHeight >= scrollHeight - 50) {
      if (hasNextPage && !isFetchingNextPage) {
        fetchNextPage();
      }
    }
  };
  return (
    <>
      {isLoadingOrderDetails && <Loader />}
      <TitleCard
        title="Orders Details"
        secondary={
          <Stack display={'flex'} flexDirection={'row'} alignItems={'center'} gap={2}>
            {startdate && enddate && (
              <Stack direction="row" spacing={2}>
                <Badge
                  badgeContent={`${statusCount}`}
                  max={99999}
                  color="primary"
                  sx={{
                    bgcolor: '#f3e5f5',
                    p: 0.2,
                    borderRadius: '3px',
                    color: '#7b1fa2'
                  }}
                >{`Orders-${datestatus}`}</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) && (
              <div>
                <Stack direction="row" spacing={2}>
                  <Chip label="Orders-All" color="primary" variant="light" size="small" />
                  {/* <Chip label={<Typography noWrap color="secondary">ALL</Typography>} variant="combined" color='warning' size='small' /> */}
                </Stack>
              </div>
            )}
            <CSVExport data={csvData} filename={`Orders_Detail_${dayjs().format('YYYY-MM-DD_HHmmss')}.csv`} />
          </Stack>
        }
      />
      <MainCard
        content={false}
        title={
          <Stack sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: 2, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
            {tenantLocations.length == 1 ? (
              <TextField
                // disabled={!isAppLocation || !isClient}
                variant="outlined"
                fullWidth
                label={'Business Location'}
                value={tenantLocations[0].locationname}
                focused
                sx={{ minWidth: 250, maxWidth: 400, flex: 1 }}
                InputProps={{
                  style: { color: theme.palette.primary.main },
                  startAdornment: (
                    <InputAdornment position="start">
                      <MyLocationIcon color="primary" />
                    </InputAdornment>
                  )
                }}
              />
            ) : (
              <Autocomplete
                fullWidth
                sx={{ minWidth: 250, maxWidth: 400, flex: 1 }}
                id="combo-box-demo"
                options={tenantLocations || []}
                getOptionLabel={(option) => `${option.locationname} (${option.suburb})` || ''}
                renderInput={(params) => <TextField {...params} label={locoName} color="primary" />}
                onChange={(event, value, reason) => {
                  if (value) {
                    console.log('Business Locations', value);
                    setLocationId(value.locationid);
                    setLocoName(value.locationname);
                  }
                  if (reason == 'clear') {
                    setLocationId(0);
                    setLocoName('Select Location');
                  }
                }}
              />
            )}

            <Autocomplete
              fullWidth
              sx={{ minWidth: 250, maxWidth: 400, flex: 1 }}
              id="combo-box-demo"
              options={status}
              getOptionLabel={(option) => `${option.status}`}
              onChange={(event, value, reason) => {
                if (reason === 'clear') {
                  setCurrentStatus('All');
                } else {
                  console.log('status', value);
                  setCurrentStatus(value.statusLow);
                }
              }}
              renderInput={(params) => <TextField {...params} label={'Select Status'} />}
            />
            <FormControl sx={{ minWidth: 250, maxWidth: 400, flex: 1 }}>
              <OutlinedInput
                inputRef={textFieldRef}
                aria-describedby="header-search-text"
                inputProps={{
                  'aria-label': 'weight'
                }}
                sx={{ background: 'white' }}
                size="large"
                id="header-search"
                placeholder="Search (ctrl+k)"
                value={searchword}
                onChange={(e) => {
                  setSearchword(e.target.value);
                }}
                autoComplete="off"
                startAdornment={
                  <InputAdornment position="start" sx={{ mr: -0.5 }}>
                    <SearchOutlined />
                  </InputAdornment>
                }
                endAdornment={
                  <Tooltip title="clear">
                    <IconButton
                      sx={{ visibility: searchword ? 'visible' : 'hidden' }}
                      onClick={() => {
                        setSearchword('');
                      }}
                    >
                      <ClearIcon style={{ fontSize: 'medium', color: '#65387A' }} />
                    </IconButton>
                  </Tooltip>
                }
              />
            </FormControl>

            {/* <Tooltip title="Order Filter">
              <IconButton
                color="secondary"
                variant="light"
                sx={{
                  color: 'text.primary',
                  bgcolor: 'grey.200',
                  mx: 2
                }}
                aria-haspopup="true"
                onClick={() => setOpen(true)}
              >
                <FilterList />
              </IconButton>
            </Tooltip> */}
          </Stack>
        }
      >
        <TableContainer
          onScroll={handleScroll}
          ref={containerRef}
          sx={{
            minHeight: 'auto',
            maxHeight: '65vh',
            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 stickyHeader aria-label="sticky table">
            <TableHead
              sx={{
                '& th': {
                  borderTop: `1px solid ${theme.palette.divider}`,
                  borderBottom: `2px solid ${theme.palette.divider} !important`
                }
              }}
            >
              <TableRow>
                <TableCell sx={{ position: 'sticky !important' }}># </TableCell>
                {/* <TableCell sx={{ position: 'sticky !important' }}> {<SlLocationPin style={{ fontWeight: 1000 }} />}</TableCell> */}
                <TableCell sx={{ whiteSpace: 'nowrap', position: 'sticky !important' }}>Location </TableCell>
                <TableCell sx={{ position: 'sticky !important' }}>Pickup </TableCell>
                <TableCell sx={{ position: 'sticky !important' }}> Drop </TableCell>
                <TableCell sx={{ position: 'sticky !important' }}> Status </TableCell>
                <TableCell sx={{ position: 'sticky !important' }}> Assigned </TableCell>
                <TableCell sx={{ position: 'sticky !important' }}> Accepted </TableCell>
                <TableCell sx={{ position: 'sticky !important' }}> Arrived </TableCell>
                <TableCell sx={{ position: 'sticky !important' }}> Picked </TableCell>
                <TableCell sx={{ position: 'sticky !important' }}> Delivered</TableCell>
                <TableCell sx={{ position: 'sticky !important' }}> Cancelled </TableCell>
                {/* <TableCell sx={{ position: 'sticky !important' }}> Notes </TableCell> */}
                <TableCell sx={{ position: 'sticky !important' }}> Kms </TableCell>
                <TableCell sx={{ position: 'sticky !important' }}> Charges </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {rows?.length == 0 && (
                <>
                  <TableCell colSpan={15}>
                    <Stack width={'100%'} direction={'row'} justifyContent={'center'}>
                      <Empty />
                    </Stack>
                  </TableCell>
                </>
              )}
              {rows?.map((row, index) => {
                return (
                  rows?.length !== 0 && (
                    <TableRow>
                      <TableCell sx={{ width: '10px' }}>{index + 1}</TableCell>
                      {/* <TableCell
                        sx={{ width: '10px', cursor: 'pointer' }}
                        onClick={() => {
                          console.log('row', row);
                          setMapTenant(row);
                          setMapOpen(true);
                          getdeliverylogs(row.deliveryid);
                        }}
                      >
                        {<SlLocationPin />}
                      </TableCell> */}
                      <TableCell
                        sx={{
                          textAlign: 'start',
                          whiteSpace: 'nowrap'
                        }}
                      >
                        {row.locationname}
                        <Typography variant="body2" noWrap>
                          {row.orderid}
                        </Typography>
                        <Tooltip title="Delivery Date">
                          <Box sx={{ cursor: 'pointer' }}>
                            <Typography noWrap sx={{ fontSize: '11px' }}>
                              {dayjs(row.deliverydate).utc().format('DD/MM/YYYY')}
                            </Typography>

                            <Typography noWrap sx={{ fontSize: '11px' }}>
                              {dayjs(row.deliverydate).utc().format('hh:mm A')}
                            </Typography>
                          </Box>
                        </Tooltip>
                      </TableCell>
                      <TableCell align="left">
                        <Stack direction={'row'} spacing={1}>
                          <Stack direction="column" sx={{ whiteSpace: 'nowrap' }}>
                            <Typography variant="caption">{row.pickupcustomer}</Typography>
                            <Typography variant="caption" color="textSecondary">
                              {row.pickupcontactno}
                            </Typography>
                            <Tooltip title={row.Pickupaddress}>
                              <Typography variant="caption" color="textSecondary" sx={{ cursor: 'pointer' }}>
                                {row.pickupsuburb || row.pickuplocation || row.Pickupaddress.slice(0, 20)}
                              </Typography>
                            </Tooltip>
                          </Stack>
                        </Stack>
                      </TableCell>
                      <TableCell align="left">
                        <Stack direction={'row'} spacing={1}>
                          <Stack direction="column" sx={{ whiteSpace: 'nowrap' }}>
                            <Typography variant="caption">{row.deliverycustomer}</Typography>
                            <Typography variant="caption" color="textSecondary">
                              {row.deliverycontactno}
                            </Typography>
                            <Tooltip title={row.deliveryaddress}>
                              <Typography variant="caption" color="textSecondary" sx={{ cursor: 'pointer' }}>
                                {/* {row.Pickupaddress.slice(0, 20)} */}
                                {row.deliverysuburb || row.deliverylocation || row.deliveryaddress.slice(0, 20)}
                              </Typography>
                            </Tooltip>
                          </Stack>
                        </Stack>
                      </TableCell>
                      <TableCell align="left">
                        <Stack direction="row">
                          {row.orderstatus === 'created' && <Chip label="Created" color="primary" size="small" sx={{ minWidth: 80 }} />}
                          {row.orderstatus === 'pending' && <Chip label="Pending" color="warning" size="small" sx={{ minWidth: 80 }} />}
                          {row.orderstatus === 'accepted' && (
                            <Chip label="Accepted" size="small" sx={{ bgcolor: theme.palette.chip.accept, color: 'white', minWidth: 80 }} />
                          )}
                          {row.orderstatus === 'arrived' && (
                            <Chip label="Arrived" size="small" sx={{ bgcolor: theme.palette.chip.arrive, color: 'white', minWidth: 80 }} />
                          )}
                          {row.orderstatus === 'picked' && <Chip label="Picked" color="info" size="small" sx={{ minWidth: 80 }} />}
                          {row.orderstatus === 'active' && <Chip label="Active" color="info" size="small" sx={{ minWidth: 80 }} />}
                          {row.orderstatus === 'delivered' && <Chip label="Delivered" color="success" size="small" sx={{ minWidth: 80 }} />}
                          {row.orderstatus === 'skipped' && <Chip label="Skipped" color="secondary" size="small" sx={{ minWidth: 80 }} />}

                          {row.orderstatus === 'cancelled' && <Chip label="Cancelled" color="error" size="small" sx={{ minWidth: 80 }} />}
                        </Stack>
                      </TableCell>
                      <TableCell align="left">
                        <Typography variant="h5" sx={{ fontSize: '11px' }} display="block">
                          {row.ridername}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '11px' }}>
                          {/* {dayjs(row.pending).format('DD/MM/YYYY')} */}
                          {row.assigntime === '' ? '' : formatDate(row.assigntime)}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '11px' }}>
                          {row.assigntime === '' ? '' : formatTime(row.assigntime)}
                        </Typography>
                      </TableCell>
                      <TableCell align="left">
                        {' '}
                        <Typography noWrap sx={{ fontSize: '11px' }}>
                          {row.starttime === '' ? '' : formatDate(row.starttime)}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                          {row.starttime === '' ? '' : formatTime(row.starttime)}
                        </Typography>
                      </TableCell>
                      <TableCell align="left">
                        {' '}
                        <Typography noWrap sx={{ fontSize: '11px' }}>
                          {row.arrivaltime === '' ? '' : formatDate(row.arrivaltime)}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                          {row.arrivaltime === '' ? '' : formatTime(row.arrivaltime)}
                        </Typography>
                      </TableCell>
                      <TableCell align="left">
                        {' '}
                        <Typography noWrap sx={{ fontSize: '11px' }}>
                          {row.pickuptime === '' ? '' : formatDate(row.pickuptime)}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                          {row.pickuptime === '' ? '' : formatTime(row.pickuptime)}
                        </Typography>
                      </TableCell>
                      <TableCell align="left">
                        {' '}
                        <Typography noWrap sx={{ fontSize: '11px' }}>
                          {row.deliverytime === '' ? '' : formatDate(row.deliverytime)}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                          {row.deliverytime === '' ? '' : formatTime(row.deliverytime)}
                        </Typography>
                      </TableCell>
                      <TableCell align="left">
                        {' '}
                        <Typography noWrap sx={{ fontSize: '11px' }}>
                          {row.canceltime === '' ? '' : formatDate(row.canceltime)}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                          {row.canceltime === '' ? '' : formatTime(row.canceltime)}
                        </Typography>
                      </TableCell>

                      {/* <TableCell align="left">
                        <Typography variant="caption">{row.ordernotes}</Typography>
                      </TableCell> */}

                      <TableCell align="left">
                        <Stack direction={'column'} spacing={1}>
                          <Chip
                            label={
                              row.orderstatus === 'cancelled' || row.orderstatus === 'cancelled' || row.kms == ''
                                ? parseInt(0).toFixed(1)
                                : parseInt(row.kms).toFixed(1)
                            }
                            size="small"
                            variant="contained"
                            color="warning"
                          />

                          {/* <Tooltip title="Actual KMS">
                            <Chip
                              label={
                                row.deliverystatus === 'cancelled' || row.actualkms === '' || row.actualkms === 'null'
                                  ? '0.0'
                                  : // : parseFloat(row.actualkms).toFixed(2)
                                    row.actualkms
                              }
                              size="small"
                              color="success"
                              variant="light"
                            />
                          </Tooltip> */}
                        </Stack>
                      </TableCell>
                      <TableCell align="right">
                        <Stack direction={'column'} spacing={1}>
                          <Chip
                            label={
                              row.orderstatus === 'cancelled' || row.deliverycharges == '' ? `₹ ${0}.00` : `₹ ${row.deliverycharges}.00`
                            }
                            size="small"
                            variant="contained"
                            color="primary"
                          />

                          {/* <Tooltip title="Delivery Amount">
                            <Chip
                              label={row.deliveryamt == '' ? `₹ ${0}.00` : `₹ ${row.deliveryamt}.00`}
                              size="small"
                              color="success"
                              variant="light"
                            />
                          </Tooltip> */}
                        </Stack>
                      </TableCell>
                    </TableRow>
                  )
                );
              })}

              {rows?.length != 0 && (
                <TableRow>
                  <TableCell colSpan={15} rowSpan={3}>
                    <div ref={loadMoreRef} style={{ height: 40, textAlign: 'center' }}>
                      {isFetchingNextPage ? <CircularProgress /> : hasNextPage ? <CircularProgress /> : 'No More Orders'}
                    </div>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>

        <Divider />
      </MainCard>
      {/* ========================================= || bottom row || ========================================= */}

      <Stack
        direction={'row'}
        sx={{
          display: 'flex',
          justifyContent: 'end',
          bgcolor: '#eeeeee'
        }}
      >
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'end',
            margin: '10px '
          }}
        >
          <Typography variant="h5">Total Charges :</Typography>
          <Tooltip title="Total Charges">
            <Chip label={formatNumberToRupees(totalCharge)} size="medium" color="error" variant="filled" sx={{ ml: 5, mr: 1.5 }} />
          </Tooltip>
        </div>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'end',
            margin: '10px '
          }}
        >
          <Typography variant="h5">Total Amount :</Typography>
          <Tooltip title="Total Charge">
            <Chip label={formatNumberToRupees(totalAmount)} size="medium" color="success" variant="filled" sx={{ ml: 5, mr: 1.5 }} />
          </Tooltip>
        </div>
      </Stack>
      {/* ========================================= || Date 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>
      {/* ========================================= || MapWithRoute || ========================================= */}
      <Dialog
        open={mapOpen}
        onClose={() => {
          setMapOpen(false);
        }}
        maxWidth={'lg'}
        fullWidth
      >
        {riderCoordinates && (
          <div>
            <MapWithRoute
              coordinates={riderCoordinates}
              additionalProps={{ riderStart, riderEnd }}
              order={mapTenant}
              setMapOpen={setMapOpen}
            />
          </div>
        )}
      </Dialog>
    </>
  );
}
