import { React, useState, useEffect, useRef } from 'react';
import TitleCard from 'pages/titleCard';
import axios from 'axios';
import { useQuery } from '@tanstack/react-query';
import { Empty } from 'antd';
// material-ui
import {
  Box,
  Divider,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
  Stack,
  IconButton,
  Tooltip,
  Chip,
  Autocomplete,
  TextField,
  Collapse,
  Backdrop
} from '@mui/material';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import dayjs from 'dayjs';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
import { CalendarMonth, FilterList } from '@mui/icons-material';
import { getreportlocationsummary, getreportsummary, gettenantlocations, getTenants } from 'pages/api/api';
import MainCard from 'components/MainCard';
import Loader from 'components/Loader';
import { useTheme } from '@mui/material/styles';
import DateFilterDialog from 'components/DateFilterDialog';
import CircularLoader from 'components/CircularLoader';
import LocationAutocomplete from 'components/nearle_components/LocationAutocomplete';
import { OpenToast } from 'components/third-party/OpenToast';
import { OrdersTableSkeleton } from '../orders/OrdersTableSkeleton';

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

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

export default function OrdersReport() {
  // const [rows, setRows] = useState([]);
  const theme = useTheme();
  const locationRef = useRef(null);
  const containerRef = useRef();
  const tenantRef = useRef(null);
  const [appId, setAppId] = useState(0);
  const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
  const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));
  const [locaName, setLocoName] = useState('All');
  const [open, setOpen] = useState(false);
  const [openRow, setOpenRow] = useState(null);
  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 [ridersdata, setRidersdata] = useState([]);
  const [locations, setLocations] = useState('Select Location');
  const userid = localStorage.getItem('userid');
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(0);
  const [locationid, setLocationid] = useState(0);
  const [tenantid, setTenantid] = useState(0);
  const [tenantValue, setTenantValue] = useState(null);
  const [locationValue, setLocationValue] = useState(null);

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

  // to clear the tenant and location and rider autocomplete
  useEffect(() => {
    setTenantid(0);
    setTenantValue(null);
    setLocationid(0);
    setLocationValue(null);
    setOpenRow(null);
  }, [appId]);
  // to clear the location and rider autocomplete
  useEffect(() => {
    setLocationid(0);
    setLocationValue(null);
    setOpenRow(null);
  }, [tenantid]);

  // table header
  const headCells = [
    {
      id: 's.no',
      numeric: false,
      disablePadding: true,
      label: '#',
      rowSpan: 2,
      colSpan: 1,
      bgcolor: '#f3e5f5'
    },
    {
      id: 'clients',
      numeric: 'true',
      disablePadding: false,
      label: tenantid ? 'Location' : 'Tenant',
      rowSpan: 2,
      colSpan: 1,
      bgcolor: '#f3e5f5'
    },
    {
      id: 'all',
      numeric: 'center',
      disablePadding: false,
      label: 'All',
      rowSpan: 2,
      colSpan: 1,
      bgcolor: '#f3e5f5'
    },

    {
      id: 'orders',
      numeric: 'center',
      disablePadding: false,
      label: 'orders',
      rowSpan: 1,
      colSpan: 3,
      bgcolor: '#ffcdd2'
    },
    {
      id: 'deliveries',
      numeric: 'center',
      disablePadding: false,
      label: 'deliveries',
      rowSpan: 1,
      colSpan: 3,
      bgcolor: '#f8bbd0'
    },
    {
      id: 'Charges',
      numeric: 'center',
      disablePadding: false,
      label: 'Collection Amt',
      rowSpan: 2,
      colSpan: 1,
      bgcolor: '#f3e5f5'
    },
    {
      id: 'kilometer',
      numeric: 'center',
      disablePadding: false,
      label: 'Kms/Actual Kms',
      rowSpan: 2,
      colSpan: 1,
      bgcolor: '#f3e5f5'
    },

    {
      id: 'Amount',
      numeric: 'center',
      disablePadding: true,
      label: 'Amount',
      rowSpan: 2,
      colSpan: 1,
      bgcolor: '#f3e5f5'
    },
    {
      id: 'action',
      numeric: 'center',
      disablePadding: true,
      label: 'Action',
      rowSpan: 2,
      colSpan: 1,
      bgcolor: '#f3e5f5'
    }
  ];

  const headCells1 = [
    {
      id: 'pending',
      numeric: false,
      disablePadding: false,
      label: 'pending',
      rowSpan: 1,
      colSpan: 1,
      bgcolor: '#ffcdd2'
    },
    {
      id: 'cancelled',
      numeric: false,
      disablePadding: false,
      label: 'cancelled',
      rowSpan: 1,
      colSpan: 1,
      bgcolor: '#ffcdd2'
    },
    {
      id: 'completed',
      numeric: false,
      disablePadding: false,
      label: 'completed',
      rowSpan: 1,
      colSpan: 1,
      bgcolor: '#ffcdd2'
    },

    {
      id: 'pending',
      numeric: false,
      disablePadding: false,
      label: 'pending',
      rowSpan: 1,
      colSpan: 1,
      bgcolor: '#f8bbd0'
    },

    {
      id: 'cancelled',
      numeric: false,
      disablePadding: false,
      label: 'cancelled',
      rowSpan: 1,
      colSpan: 1,
      bgcolor: '#f8bbd0'
    },
    {
      id: 'completed',
      numeric: false,
      disablePadding: false,
      label: 'completed',
      rowSpan: 1,
      colSpan: 1,
      bgcolor: '#f8bbd0'
    }
  ];
  const getColorByValue = (value) => {
    return Number(value) !== 0 ? 'red' : 'inherit';
  };
  const coloredCell = (value) => <Typography sx={{ color: getColorByValue(value) }}>{value}</Typography>;

  // ==============================|| MUI TABLE - HEADER ||============================== //

  function EnhancedTableHead() {
    return (
      <TableHead>
        <TableRow>
          {headCells.map((headCell) => (
            <TableCell
              key={headCell.id}
              align={headCell.numeric == 'center' ? 'center' : headCell.numeric == 'true' ? 'left' : 'right'}
              padding={headCell.disablePadding ? 'none' : 'normal'}
              rowSpan={headCell.rowSpan}
              colSpan={headCell.colSpan}
              sx={{ bgcolor: headCell.bgcolor }}
            >
              {headCell.label}
            </TableCell>
          ))}
        </TableRow>
        <TableRow>
          {headCells1.map((headCell) => (
            <TableCell
              key={headCell.id}
              align={headCell.numeric ? 'right' : 'left'}
              padding={headCell.disablePadding ? 'none' : 'normal'}
              rowSpan={headCell.rowSpan}
              colSpan={headCell.colSpan}
              sx={{ bgcolor: headCell.bgcolor }}
            >
              {headCell.label}
            </TableCell>
          ))}
        </TableRow>
      </TableHead>
    );
  }

  // ==============================|| fetchOrdersSummary (orders summary)||============================== //
  const {
    data: rows,
    isLoading: isLoadingReports,
    isError: isErrorReports, //true or false
    error: reportsError
  } = useQuery({
    queryKey: [appId, tenantid, locationid, startdate, enddate],
    queryFn: tenantid ? getreportlocationsummary : getreportsummary
  });
  // ==============================|| getTenants ||============================== //

  const {
    data: tenantlist,
    isLoading: fetchtenantsIsLoading,
    isError: fetchtenantsIsError,
    error: fetchtenantsError
  } = useQuery({
    queryKey: ['tenantlist', appId],
    queryFn: () => getTenants(appId), // Ensure appId is passed
    enabled: appId !== 0 // Ensures query runs only when appId is valid
  });
  // ==============================|| gettenantlocations ||============================== //

  const {
    data: locationlist,
    isLoading: fetchlocationsIsLoading,
    isError: fetchlocationsIsError,
    error: fetchlocationsError
  } = useQuery({
    queryKey: ['gettenantlocations', tenantid],
    queryFn: () => gettenantlocations(tenantid), // Ensure appId is passed
    enabled: tenantid !== 0 // Ensures query runs only when appId is valid
  });
  // ==============================|| fetchridersummary by tenid (orders summary)||============================== //
  const fetchridersummary = async (tenantid) => {
    setLoading(true);
    try {
      const riderRes = await axios.get(
        `${process.env.REACT_APP_URL}/deliveries/getridersummary/?&tenantid=${tenantid}&fromdate=${startdate}&todate=${enddate}`
      );
      console.log('riderRes', riderRes.data.details);
      setRidersdata(riderRes.data.details);
    } catch (error) {
      console.log('riderRes', error);
    } finally {
      setLoading(false);
    }
  };
  // ==============================|| getuserreportsummary by tenid (orders summary)||============================== //
  const getuserreportsummary = async (tenantid) => {
    setLoading(true);
    try {
      const riderRes = await axios.get(
        `${process.env.REACT_APP_URL}/deliveries/getuserreportsummary/?&tenantid=${tenantid}&fromdate=${startdate}&todate=${enddate}`
      );
      console.log('riderRes', riderRes.data.details);
      setRidersdata(riderRes.data.details);
    } catch (error) {
      console.log('riderRes', error);
    } finally {
      setLoading(false);
    }
  };
  // ==============================|| 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]);

  // ==============================|| fetchAppLocations ||============================== //
  const fetchAppLocations = async () => {
    try {
      const locationRes = await axios.get(`${process.env.REACT_APP_URL}/partners/getlocations/?userid=${userid}`);
      const updatedLocations = [
        ...locationRes.data.details,
        { locationname: 'All', applocationid: 0 } // Add your new object here
      ];
      console.log('fetchAppLocations', updatedLocations);
      setLocations(updatedLocations);
    } catch (err) {
      console.log('locationRes', err);
    }
  };
  useEffect(() => {
    fetchAppLocations();
  }, []);

  if (isErrorReports) console.log('An error has occurred:(isErrorReports) ' + reportsError.message);

  return (
    <>
      {(loading || isLoadingReports) && (
        <>
          {/* <CircularLoader /> */}
          <Loader />
        </>
      )}

      {/* <Backdrop
        sx={{
          color: '#fff',
          zIndex: (theme) => theme.zIndex.drawer + 1
        }}
        open={loading || isLoadingReports} // when loader = true, backdrop covers the page
      >
        <CircularLoader color="inherit" />
      </Backdrop> */}

      <TitleCard
        title="Orders Summary"
        secondary={
          <LocationAutocomplete
            ref={locationRef}
            locaName={locaName}
            setAppId={setAppId}
            setLocoName={setLocoName}
            setPage={setPage}
            sx={{ minWidth: 280, width: '100%', flex: { custom550: 0 } }}
          />
        }
      />

      <Stack
        display={'flex'}
        flexDirection={'row'}
        alignItems={'center'}
        justifyContent={'space-between'}
        flexWrap={'wrap'}
        gap={1}
        sx={{ border: '1px solid', borderColor: 'bg.main', p: 2 }}
      >
        <Stack>
          {startdate && enddate && (
            <Stack direction="row" gap={2} flexWrap={'wrap'}>
              <Chip label={`Orders-${datestatus}`} color="primary" variant="light" size="small" />
              <Tooltip title="Date Filter" placement="top">
                <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' }}
                />
              </Tooltip>
            </Stack>
          )}
        </Stack>
        <Stack
          sx={{
            display: 'flex',
            flexDirection: 'row',
            gap: 2,
            flexWrap: 'wrap',
            flexGrow: 1,
            justifyContent: { xs: 'start', custom950: 'right' }
          }}
        >
          <Autocomplete
            options={tenantlist || []}
            value={tenantValue}
            sx={{ minWidth: 250, flex: { xs: 1, custom950: 0 } }}
            onOpen={(event) => {
              if (!appId) {
                event.preventDefault();
                OpenToast('Please select a your app location first!', 'warning', 3000);
                setTimeout(() => {
                  locationRef.current?.focus();
                }, 0);
              }
            }}
            onChange={(e, val, reason) => {
              if (reason === 'clear') {
                setTenantid(0);
                setTenantValue(null);
                setLocationid(0);
                setLocationValue(null);
              } else {
                setTenantid(val?.tenantid || 0);
                setTenantValue(val);
                setLocationid(val.locationid);
                setLocationValue(null);
              }
            }}
            renderInput={(params) => <TextField {...params} inputRef={tenantRef} label="Select Tenant" />}
          />
          {/* ==================================================== || Location Autocomplete || ====================================================  */}
          <Autocomplete
            options={locationlist || []}
            getOptionLabel={(option) => `${option.locationname} (${option.suburb})` || ''}
            value={locationValue}
            sx={{ minWidth: 250, flex: { xs: 1, custom950: 0 } }}
            onOpen={(event) => {
              if (!appId && !tenantid) {
                event.preventDefault();
                OpenToast('Please select a your Location and Tenant first!', 'warning', 3000);
                setTimeout(() => {
                  locationRef.current?.focus();
                }, 0);
              } else if (!tenantid) {
                event.preventDefault();
                OpenToast('Please select a your  Tenant first!', 'warning', 3000);
                setTimeout(() => {
                  tenantRef.current?.focus();
                }, 0);
              }
            }}
            onChange={(e, val, reason) => {
              if (reason === 'clear') {
                setLocationid(0);
                setLocationValue(null);
              } else {
                setLocationid(val.locationid || 0);
                setLocationValue(val);
              }
            }}
            renderInput={(params) => <TextField {...params} label="Select Location" />}
          />
        </Stack>
      </Stack>
      <MainCard content={false}>
        <TableContainer
          sx={{
            overflow: 'auto',
            '&::-webkit-scrollbar': {
              width: '12px', // scroll bar width
              cursor: 'pointer'
            },
            '&::-webkit-scrollbar-thumb': {
              backgroundColor: theme.palette.primary.main, // thumb color
              borderRadius: '8px',
              cursor: 'pointer'
            },
            '&::-webkit-scrollbar-thumb:hover': {
              backgroundColor: theme.palette.primary.dark, // hover color
              cursor: 'pointer'
            },
            '&::-webkit-scrollbar-track': {
              backgroundColor: theme.palette.primary.lighter,
              cursor: 'pointer'
            }
          }}
        >
          <Table>
            {/* ============================================ ||EnhancedTableHead || ============================================ */}

            <EnhancedTableHead />
            {/* ============================================ || TableBody || ============================================ */}

            <TableBody>
              {isLoadingReports && <OrdersTableSkeleton col={8} />}
              {rows?.length == 0 && (
                <TableRow>
                  <TableCell colSpan={13} rowSpan={40}>
                    <Stack width={'100%'} direction={'row'} justifyContent={'center'}>
                      <Empty />
                    </Stack>
                  </TableCell>
                </TableRow>
              )}
              {(rows?.length != 0 || rows) &&
                rows?.map((row, index) => (
                  <>
                    {/* ============================================ || tablerow 1 || ============================================ */}

                    <TableRow
                      key={row.tenantname || row.locationname}
                      // sx={{
                      //   cursor: openRow === row.tenantname ? 'pointer' : null
                      // }}
                    >
                      <TableCell>{index + 1}</TableCell>
                      <TableCell align="left">
                        <Stack spacing={1}>
                          <Typography sx={{ whiteSpace: 'noWrap' }}>{tenantid ? row.locationname : row.tenantname} </Typography>
                          <Typography variant="subtitle2">Id : {tenantid ? row.locationid : row.tenantid} </Typography>
                        </Stack>
                      </TableCell>
                      <TableCell align="center">{coloredCell(row.totalorders)}</TableCell>
                      <TableCell align="center">{coloredCell(row.Orderspending)}</TableCell>
                      <TableCell align="center">{coloredCell(row.orderscancelled)}</TableCell>
                      <TableCell align="center">{coloredCell(row.orderscompleted)}</TableCell>
                      <TableCell align="center">{coloredCell(row.deliveriespending)}</TableCell>
                      <TableCell align="center">{coloredCell(row.deliveriescancelled)}</TableCell>
                      <TableCell align="center">{coloredCell(row.deliveriescompleted)}</TableCell>
                      <TableCell align="center">
                        {/* <Tooltip title="Cash on Delivery" placement="top">
                          <Chip
                            size="small"
                            label={`₹${Number(row.payondelivery).toFixed(2)}`}
                            variant="combined"
                            color={row.payondelivery ? 'error' : 'secondary'}
                            sx={{
                              mb: 1,
                              cursor: 'pointer',
                              minWidth: 80
                            }}
                          />
                        </Tooltip>
                        <br /> */}
                        {/* <Tooltip title="Pay Later" placement="bottom"> */}
                        <Chip
                          size="small"
                          label={`₹${Number(row.collectionamt).toFixed(2)}`}
                          variant="combined"
                          color={row.collectionamt ? 'warning' : 'secondary'}
                          sx={{
                            cursor: 'pointer',
                            minWidth: 80
                          }}
                        />
                        {/* </Tooltip> */}
                      </TableCell>{' '}
                      <TableCell align="center">
                        <Tooltip title="kms" placement="top">
                          <Chip
                            size="small"
                            label={`${Number(row.kms).toFixed(2)}`}
                            color={row.kms ? 'error' : 'secondary'}
                            variant="combined"
                            sx={{
                              mb: 1,
                              cursor: 'pointer',
                              minWidth: 80
                            }}
                          />
                        </Tooltip>

                        <br />
                        <Tooltip title="Actual kms" placement="bottom">
                          <Chip
                            size="small"
                            label={Number(row.cumulativekms).toFixed(2)}
                            color={row.cumulativekms ? 'success' : 'secondary'}
                            variant="combined"
                            sx={{
                              cursor: 'pointer',
                              minWidth: 80
                            }}
                          />
                        </Tooltip>
                      </TableCell>
                      <TableCell align="right">
                        <Tooltip title="Delivery Amount" placement="top">
                          <Chip
                            size="small"
                            label={formatNumberToRupees(row.charges >= row.deliveryamt ? row.charges : row.deliveryamt)}
                            color={row.deliveryamt || row.charges ? 'primary' : 'secondary'}
                            variant="combined"
                            sx={{
                              cursor: 'pointer',
                              minWidth: 100
                            }}
                          />
                        </Tooltip>
                      </TableCell>
                      <TableCell align="center">
                        <IconButton
                          aria-label="expand row"
                          size="small"
                          // onClick={() => {
                          //   setRidersdata([]); // yo avoid appending new data list to exiting
                          //   setTimeout(() => {
                          //     openRow !== row.tenantname && (tenantid
                          //       ? getriderlocationsummary(row.locationid)
                          //       : getuserreportsummary(row.tenantid));
                          //     setOpenRow(openRow === row.tenantname ? null : row.tenantname);
                          //   }, 0);
                          // }}
                          onClick={() => {
                            if (tenantid) {
                              // if tenant selected and shows the location list
                              const isOpening = openRow !== row.tenantname;
                              // toggle row
                              setOpenRow(isOpening ? row.tenantname : null);
                              if (!isOpening) return; // ❌ closing → don't call API
                              // clear old data only when opening
                              setRidersdata([]);
                              // ✅ call correct API
                              getriderlocationsummary(row.locationid);
                            } else {
                              const isOpening = openRow !== row.locationname;

                              // toggle row
                              setOpenRow(isOpening ? row.locationname : null);

                              if (!isOpening) return; // ❌ closing → don't call API

                              // clear old data only when opening
                              setRidersdata([]);

                              // ✅ call correct API

                              getuserreportsummary(row.tenantid);
                            }
                          }}
                          sx={{
                            bgcolor: openRow === row.tenantname ? 'primary.main' : null,
                            color: openRow === row.tenantname ? 'white' : null,
                            '&:hover': {
                              bgcolor: openRow === row.tenantname ? 'primary.main' : '#e1bee7'
                            }
                          }}
                        >
                          <Tooltip title="View Riders" placement="top">
                            {tenantid ? (
                              openRow === row.tenantname ? (
                                <KeyboardArrowUpIcon />
                              ) : (
                                <KeyboardArrowDownIcon />
                              )
                            ) : openRow === row.locationname ? (
                              <KeyboardArrowUpIcon />
                            ) : (
                              <KeyboardArrowDownIcon />
                            )}
                          </Tooltip>
                        </IconButton>
                      </TableCell>
                    </TableRow>
                    {/* ============================================ || collapsive row || ============================================ */}

                    {(tenantid ? openRow === row.tenantname : openRow === row.locationname) && (
                      <TableRow
                      // sx={{
                      //   cursor: openRow === row.tenantname ? 'pointer' : null,
                      //   '&:hover': {
                      //     bgcolor: 'white!important'
                      //   }
                      // }}
                      >
                        <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={15}>
                          <Box sx={{ margin: 1, border: '1px solid', borderColor: 'secondary.lighter' }}>
                            <Table size="small">
                              <TableHead>
                                <TableRow sx={{ bgcolor: 'primary.lighter' }}>
                                  <TableCell>#</TableCell>
                                  <TableCell>Rider</TableCell>
                                  <TableCell align="center">Orders</TableCell>
                                  <TableCell align="center">Deliveries</TableCell>
                                  <TableCell align="center">Pending</TableCell>
                                  <TableCell align="center">Cancelled</TableCell>
                                  <TableCell align="center">Completed</TableCell>
                                  <TableCell align="center">Collection Amt</TableCell>
                                  <TableCell align="center">kms/Actual kms</TableCell>
                                  <TableCell align="center">Charges</TableCell>
                                </TableRow>
                              </TableHead>
                              <TableBody>
                                {loading && <OrdersTableSkeleton col={5} />}
                                {/* {ridersdata?.length == 0 && (
                                  <TableRow>
                                    <TableCell colSpan={13} rowSpan={40}>
                                      <Stack width={'100%'} direction={'row'} justifyContent={'center'}>
                                        <Empty />
                                      </Stack>
                                    </TableCell>
                                  </TableRow>
                                )} */}
                                {ridersdata?.map((row, index) => (
                                  <TableRow key={row.tenantname}>
                                    <TableCell>{index + 1}</TableCell>
                                    <TableCell align="left">
                                      <Stack>
                                        <Typography sx={{ whiteSpace: 'noWrap' }}>{` ${row.firstname} ${row.lastname}`}</Typography>
                                        <Typography variant="subtitle2" sx={{ whiteSpace: 'noWrap' }}>
                                          {row.ridercontact}
                                        </Typography>
                                        <Typography variant="subtitle2" sx={{ whiteSpace: 'noWrap' }}>
                                          ID : {row.userid}
                                        </Typography>
                                      </Stack>
                                    </TableCell>

                                    <TableCell align="center">{coloredCell(row.orderscreated)}</TableCell>
                                    <TableCell align="center">{coloredCell(row.totalorders)}</TableCell>
                                    <TableCell align="center">{coloredCell(row.deliveriespending)}</TableCell>
                                    <TableCell align="center">{coloredCell(row.deliveriescancelled)}</TableCell>
                                    <TableCell align="center">{coloredCell(row.deliveriescompleted)}</TableCell>
                                    {/* <TableCell align="center">{coloredCell(row.picked)}</TableCell>
                                    <TableCell align="center">{coloredCell(row.active)}</TableCell>
                                    <TableCell align="center">{coloredCell(row.skipped)}</TableCell>
                                    <TableCell align="center">{coloredCell(row.cancelled)}</TableCell>
                                    <TableCell align="center">{coloredCell(row.delivered)}</TableCell> */}
                                    <TableCell align="center">
                                      {/* <Tooltip title="Cash on Delivery" placement="top">
                                        <Chip
                                          size="small"
                                          label={formatNumberToRupees(row.payondelivery)}
                                          color={row.payondelivery ? 'error' : 'secondary'}
                                          variant="combined"
                                          sx={{
                                            mb: 1,
                                            cursor: 'pointer',
                                            minWidth: 80
                                          }}
                                        />
                                      </Tooltip>
                                      <br /> */}
                                      {/* <Tooltip title="Paylater" placement="top"> */}
                                      <Chip
                                        size="small"
                                        label={formatNumberToRupees(row.collectionamt)}
                                        color={row.collectionamt ? 'warning' : 'secondary'}
                                        variant="combined"
                                        sx={{
                                          cursor: 'pointer',
                                          minWidth: 80
                                        }}
                                      />
                                      {/* </Tooltip> */}
                                    </TableCell>
                                    <TableCell align="center">
                                      <Tooltip title="kms" placement="top">
                                        <Chip
                                          size="small"
                                          label={row.kms.toFixed(2)}
                                          color={row.kms ? 'error' : 'secondary'}
                                          variant="combined"
                                          sx={{
                                            mb: 1,
                                            cursor: 'pointer',
                                            minWidth: 80
                                          }}
                                        />
                                      </Tooltip>
                                      <br />
                                      <Tooltip title="Actual kms" placement="top">
                                        <Chip
                                          size="small"
                                          label={row.cumulativekms.toFixed(2)}
                                          color={row.cumulativekms ? 'success' : 'secondary'}
                                          variant="combined"
                                          sx={{
                                            cursor: 'pointer',
                                            minWidth: 80
                                          }}
                                        />
                                      </Tooltip>
                                    </TableCell>

                                    <TableCell align="center">
                                      <Tooltip title="Delivery Amount" placement="top">
                                        <Chip
                                          size="small"
                                          label={formatNumberToRupees(row.charges >= row.deliveryamt ? row.charges : row.deliveryamt)}
                                          color={row.deliveryamt || row.charges ? 'primary' : 'secondary'}
                                          variant="combined"
                                          sx={{
                                            cursor: 'pointer',
                                            minWidth: 100
                                          }}
                                        />
                                      </Tooltip>
                                    </TableCell>
                                  </TableRow>
                                ))}
                              </TableBody>
                            </Table>
                          </Box>
                        </TableCell>
                      </TableRow>
                    )}
                  </>
                ))}

              {rows?.length != 0 && rows && (
                <TableRow sx={{}}>
                  <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"> {totalOrderCancel}</Typography>
                  </TableCell>
                  <TableCell align="center">
                    <Typography variant="h5">{totalOrderComplete}</Typography>
                  </TableCell>
                  <TableCell align="center">
                    <Typography variant="h5">{totalDeliPend}</Typography>
                  </TableCell>
                  <TableCell align="center">
                    <Typography variant="h5"> {totalDeliCancel}</Typography>
                  </TableCell>
                  <TableCell align="center">
                    <Typography variant="h5">{totalDeliComplete}</Typography>
                  </TableCell>
                  <TableCell></TableCell>
                  <TableCell></TableCell>
                  <TableCell align="right" sx={{ pr: -2 }}>
                    <Typography variant="h5">{formatNumberToRupees(total)}</Typography>
                  </TableCell>
                  <TableCell></TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>

        <Divider />
      </MainCard>
      {/* ============================================ || date filter dialog || ============================================ */}
      <DateFilterDialog
        open={open}
        onClose={() => setOpen(false)}
        onSelect={(range) => {
          setStartdate(range.startDate);
          setEnddate(range.endDate);
          setDatestatus(range.label);
          console.log('Selected Date Range:', range);
        }}
      />
    </>
  );
}
