import PropTypes from "prop-types";
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";
import TaskAltIcon from "@mui/icons-material/TaskAlt";

// material-ui
import {
  Box,
  Checkbox,
  Divider,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableSortLabel,
  TableRow,
  Grid,
  Dialog,
  DialogTitle,
  Typography,
  DialogContent,
  Stack,
  Button,
  IconButton,
  Tooltip,
  Chip,
  Avatar,
  Autocomplete,
  TextField,
  FormControl,
  OutlinedInput,
  InputAdornment,
  Paper,
  Collapse,
} 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, MoreOutlined } from "@ant-design/icons";

import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import dayjs from "dayjs";
var utc = require("dayjs/plugin/utc");
dayjs.extend(utc);
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { DateRangePicker } from "mui-daterange-picker";
import {
  addDays,
  addMonths,
  addWeeks,
  // addYears,
  endOfMonth,
  endOfWeek,
  // endOfYear,
  startOfMonth,
  startOfWeek,
  // startOfYear,
} from "date-fns";
import { visuallyHidden } from "@mui/utils";
import { FilterList } from "@mui/icons-material";

// project imports
import { fetchOrdersSummary, fetchLocations } from "pages/api/api";
import MainCard from "components/MainCard";
import {
  CSVExport,
  TableRowSelection,
} from "components/third-party/ReactTable";
import Loader from "components/Loader";
import Column from "antd/es/table/Column";
import { useTheme } from "@mui/material/styles";

// table filter
function descendingComparator(a, b, orderBy) {
  if (b[orderBy] < a[orderBy]) {
    return -1;
  }
  if (b[orderBy] > a[orderBy]) {
    return 1;
  }
  return 0;
}

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

function stableSort(array, comparator) {
  const stabilizedThis = array.map((el, index) => [el, index]);
  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0]);
    if (order !== 0) return order;
    return a[1] - b[1];
  });
  return stabilizedThis.map((el) => el[0]);
}
function formatNumberToRupees(value) {
  return new Intl.NumberFormat("en-IN", {
    style: "currency",
    currency: "INR",
    minimumFractionDigits: 2,
  }).format(value);
}
// table header
const headCells = [
  {
    id: "s.no",
    numeric: false,
    disablePadding: true,
    label: "#",
    rowSpan: 2,
    colSpan: 1,
    bgcolor: "#f3e5f5",
  },
  {
    id: "clients",
    numeric: false,
    disablePadding: false,
    label: "Clients",
    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: "kilometer",
    numeric: false,
    disablePadding: false,
    label: "kilometer",
    rowSpan: 1,
    colSpan: 1,
    bgcolor: "#f3e5f5",
  },

  {
    id: "Charges",
    numeric: true,
    disablePadding: false,
    label: "Charges",
    rowSpan: 1,
    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: "completed",
    numeric: false,
    disablePadding: false,
    label: "completed",
    rowSpan: 1,
    colSpan: 1,
    bgcolor: "#ffcdd2",
  },
  {
    id: "cancelled",
    numeric: false,
    disablePadding: false,
    label: "cancelled",
    rowSpan: 1,
    colSpan: 1,
    bgcolor: "#ffcdd2",
  },
  {
    id: "pending",
    numeric: false,
    disablePadding: false,
    label: "pending",
    rowSpan: 1,
    colSpan: 1,
    bgcolor: "#f8bbd0",
  },
  {
    id: "completed",
    numeric: false,
    disablePadding: false,
    label: "completed",
    rowSpan: 1,
    colSpan: 1,
    bgcolor: "#f8bbd0",
  },
  {
    id: "cancelled",
    numeric: false,
    disablePadding: false,
    label: "cancelled",
    rowSpan: 1,
    colSpan: 1,
    bgcolor: "#f8bbd0",
  },
  {
    id: "kms / actualkms",
    numeric: false,
    disablePadding: false,
    label: "kms / actualkms",
    rowSpan: 1,
    colSpan: 1,
    bgcolor: "#f3e5f5",
  },
  {
    id: " pod / plt",
    numeric: false,
    disablePadding: false,
    label: "PLT /pod",
    rowSpan: 1,
    colSpan: 1,
    bgcolor: "#f3e5f5",
  },
];

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

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

  return (
    <TableHead>
      <TableRow>
        {/* <TableCell padding="checkbox" sx={{ pl: 3 }}>
          <Checkbox
            color="primary"
            indeterminate={numSelected > 0 && numSelected < rowCount}
            checked={rowCount > 0 && numSelected === rowCount}
            onChange={onSelectAllClick}
            inputProps={{
              "aria-label": "select all desserts",
            }}
          />
        </TableCell> */}
        {headCells.map((headCell) => (
          <TableCell
            key={headCell.id}
            align={
              headCell.numeric == "center"
                ? "center"
                : "true"
                ? "left"
                : "right"
            }
            padding={headCell.disablePadding ? "none" : "normal"}
            sortDirection={orderBy === headCell.id ? order : undefined}
            rowSpan={headCell.rowSpan}
            colSpan={headCell.colSpan}
            sx={{ bgcolor: headCell.bgcolor }}
          >
            {/* <TableSortLabel
              active={orderBy === headCell.id}
              direction={orderBy === headCell.id ? order : "asc"}
              onClick={createSortHandler(headCell.id)}
            > */}
            {headCell.label}
            {/* {orderBy === headCell.id ? (
                <Box component="span" sx={visuallyHidden}>
                  {order === "desc" ? "sorted descending" : "sorted ascending"}
                </Box>
              ) : null}
            </TableSortLabel> */}
          </TableCell>
        ))}
      </TableRow>
      <TableRow>
        {headCells1.map((headCell) => (
          <TableCell
            key={headCell.id}
            align={headCell.numeric ? "right" : "left"}
            padding={headCell.disablePadding ? "none" : "normal"}
            sortDirection={orderBy === headCell.id ? order : undefined}
            rowSpan={headCell.rowSpan}
            colSpan={headCell.colSpan}
            sx={{ bgcolor: headCell.bgcolor }}
          >
            {headCell.label}
          </TableCell>
        ))}
      </TableRow>
    </TableHead>
  );
}

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

export default function OrdersReport() {
  // const [rows, setRows] = useState([]);
  const theme = useTheme();
  const [order, setOrder] = useState("asc");
  const [orderBy, setOrderBy] = useState("calories");
  const [selected, setSelected] = useState([]);
  const [page, setPage] = useState(0);
  const [dense] = useState(false);
  const [rowsPerPage, setRowsPerPage] = useState("");
  const [selectedValue, setSelectedValue] = useState([]);
  const [startdate, setStartdate] = useState(dayjs().format("YYYY-MM-DD"));
  const [enddate, setEnddate] = useState(dayjs().format("YYYY-MM-DD"));

  const [open, setOpen] = useState(false);
  const [open1, setOpen1] = useState(false);
  // const [openRow, setOpenRow] = useState({});
  const [openRow, setOpenRow] = useState(null); // Initially no row is open

  const [dateselect, setDateselect] = useState("select");
  const [tabstatus1, setTabstatus1] = useState("Today");
  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 [id, setid] = useState(-1);
  const [searchword, setSearchword] = useState("");
  const textFieldRef = useRef(null);
  const [ridersdata, setRidersdata] = useState([]);

  const [appId, setAppId] = useState(0);
  const [locaName, setLocoName] = useState("All");
  const [locations, setLocations] = useState("All");
  /* ============================================= || 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);
    };
  }, []);

  // ==============================|| fetchOrdersSummary (orders summary)||============================== //
  const {
    isLoading: isLoadingReports,
    isError: isErrorReports, //true or false
    data: rows,
    error: reportsError,
  } = useQuery({
    queryKey: [appId, startdate, enddate],
    queryFn: fetchOrdersSummary,
  });
  // ==============================|| fetchridersummary by tenid (orders summary)||============================== //
  const fetchridersummary = async (tenid) => {
    try {
      const riderRes = await axios.get(
        `https://jupiter.nearle.app/live/api/v1/deliveries/getridersummary/?&tenantid=${tenid}&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 && setRowsPerPage(rows.length + 1);
  }, [rows]);
  // ==============================|| fetchAppLocations ||============================== //
  const fetchAppLocations = async () => {
    try {
      const locationRes = await axios.get(
        `${process.env.REACT_APP_URL}/utils/getapplocations`,
      );
      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 (isLoadingReports) return <Loader />;
  if (isErrorReports)
    return "An error has occurred:(isErrorReports) " + reportsError.message;

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

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

  const handleClick = (event, name) => {
    const selectedIndex = selected.indexOf(name);
    let newSelected = [];
    if (selectedIndex === -1) {
      newSelected = newSelected.concat(selected, name);
    } else if (selectedIndex === 0) {
      newSelected = newSelected.concat(selected.slice(1));
    } else if (selectedIndex === selected.length - 1) {
      newSelected = newSelected.concat(selected.slice(0, -1));
    } else if (selectedIndex > 0) {
      newSelected = newSelected.concat(
        selected.slice(0, selectedIndex),
        selected.slice(selectedIndex + 1),
      );
    }
    // const selectedRowData = rows.filter((row) =>
    //   newSelected.includes(row.name.toString())
    // );
    // setSelectedValue(selectedRowData);
    // setSelected(newSelected);
  };

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

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

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

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

  const filteredOrders =
    searchword == ""
      ? rows
      : rows.filter((row) =>
          row.tenantname.toLowerCase().includes(searchword.toLowerCase()),
        );

  return (
    <>
      <TitleCard title="Orders Summary" />{" "}
      <MainCard
        content={false}
        sx={{ mt: "10px" }}
        title={
          <Stack direction="column" alignItems="flex-start" spacing={1}>
            {startdate && enddate && (
              <Stack direction="row" spacing={2}>
                <Chip
                  label={`Orders-${datestatus}`}
                  color="primary"
                  variant="light"
                  size="small"
                />
                <Chip
                  label={
                    <Typography noWrap color="secondary">
                      {dayjs(startdate).format("DD/MM/YYYY")} -{" "}
                      {dayjs(enddate).format("DD/MM/YYYY")}
                    </Typography>
                  }
                  variant="combined"
                  color="warning"
                  size="small"
                />
              </Stack>
            )}
            {(!startdate || !enddate) && (
              <>
                <Stack direction="row" spacing={2}>
                  <Chip
                    label="Orders-All"
                    color="primary"
                    variant="light"
                    size="small"
                  />
                  {/* <Chip label={<Typography noWrap color="secondary">ALL</Typography>} variant="combined" color='warning' size='small' /> */}
                </Stack>
              </>
            )}
          </Stack>
        }
        secondary={
          <div style={{ display: "flex", flexDirection: "row" }}>
            <FormControl
              sx={{ width: 250, display: { xs: "none", md: "flex" }, mr: 2 }}
            >
              <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={
                  <IconButton
                    sx={{ visibility: searchword ? "visible" : "hidden" }}
                    onClick={() => {
                      setSearchword("");
                    }}
                  >
                    <ClearIcon
                      style={{ fontSize: "medium", color: "#65387A" }}
                    />
                  </IconButton>
                }
              />
            </FormControl>
            <Autocomplete
              disablePortal
              id="combo-box-demo"
              options={locations}
              getOptionLabel={(option) => `${option.locationname}`}
              sx={{ width: 300 }}
              onChange={(event, value, reason) => {
                if (reason === "clear") {
                  setAppId(0);
                  setLocoName("All");
                } else {
                  console.log(value);
                  setAppId(value.applocationid);
                  setLocoName(value.locationname);
                }
              }}
              renderInput={(params) => (
                <TextField {...params} label={locaName} />
              )}
            />

            <Tooltip title="Order Filter">
              <IconButton
                color="secondary"
                variant="light"
                sx={{
                  color: "text.primary",
                  bgcolor: "grey.200",
                  display: { xs: "none", md: "flex" },
                  ml: 2,
                }}
                aria-haspopup="true"
                onClick={() => setOpen(true)}
              >
                <FilterList />
              </IconButton>
            </Tooltip>
          </div>
        }
      >
        <TableRowSelection selected={selected.length} />

        {/* table */}
        <TableContainer>
          <Table
            // sx={{ minWidth: 750 }}
            aria-labelledby="tableTitle"
            size={dense ? "small" : "medium"}
          >
            {/* ============================================ ||EnhancedTableHead || ============================================ */}

            <EnhancedTableHead
              numSelected={selected.length}
              order={order}
              orderBy={orderBy}
              onSelectAllClick={handleSelectAllClick}
              onRequestSort={handleRequestSort}
              rowCount={rows.length}
            />
            {/* ============================================ || TableBody || ============================================ */}

            <TableBody>
              {stableSort(filteredOrders, getComparator(order, orderBy))
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                .map((row, index) => {
                  if (typeof row === "number") return null;
                  const isItemSelected = isSelected(row.name);
                  const labelId = `enhanced-table-checkbox-${index}`;

                  return filteredOrders.length !== 0 ? (
                    <>
                      {/* ============================================ || tablerow 1 || ============================================ */}

                      <TableRow
                        // hover
                        onClick={(event) => handleClick(event, row.name)}
                        role="checkbox"
                        aria-checked={isItemSelected}
                        tabIndex={-1}
                        key={row.tenantname}
                        selected={isItemSelected}
                        sx={{
                          bgcolor:
                            openRow === row.tenantname ? "#e1bee7" : null,
                          "&:hover": {
                            bgcolor:
                              openRow === row.tenantname
                                ? "#e1bee7!important"
                                : null,
                          },
                          cursor: openRow === row.tenantname ? "pointer" : null,
                        }}
                      >
                        {/* <TableCell sx={{ pl: 3 }} padding="checkbox">
                        <Checkbox
                          color="primary"
                          checked={isItemSelected}
                          inputProps={{
                            "aria-labelledby": labelId,
                          }}
                        />
                      </TableCell> */}

                        <TableCell
                          component="th"
                          id={labelId}
                          scope="row"
                          padding="none"
                        >
                          {index + 1}
                        </TableCell>
                        <TableCell align="left">
                          <Stack direction="row" sx={{ ml: -2 }}>
                            {row.tenantname}
                          </Stack>
                        </TableCell>
                        <TableCell align="center">{row.totalorders}</TableCell>
                        <TableCell align="center">
                          {row.Orderspending}
                        </TableCell>
                        <TableCell align="center">
                          {row.orderscompleted}
                        </TableCell>
                        <TableCell align="center">
                          {row.orderscancelled}
                        </TableCell>
                        <TableCell align="center">
                          {" "}
                          {row.deliveriespending}
                        </TableCell>
                        <TableCell align="center">
                          {" "}
                          {row.deliveriescompleted}
                        </TableCell>
                        <TableCell align="center">
                          {" "}
                          {row.deliveriescancelled}
                        </TableCell>
                        <TableCell align="left">
                          <Tooltip title="kms" placement="top">
                            <Chip
                              size="small"
                              label={parseFloat(row.kms).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 ",
                                minWidth: 100,
                              }}
                            />
                          </Tooltip>
                        </TableCell>
                        <TableCell align="center">
                          <IconButton
                            aria-label="expand row"
                            size="small"
                            onClick={() => {
                              fetchridersummary(row.tenantid);
                              setOpenRow(
                                openRow === row.tenantname
                                  ? null
                                  : row.tenantname,
                              );
                            }}
                            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">
                              {openRow === row.tenantname ? (
                                <KeyboardArrowUpIcon />
                              ) : (
                                <KeyboardArrowDownIcon />
                              )}
                            </Tooltip>
                          </IconButton>{" "}
                        </TableCell>
                      </TableRow>
                      {/* ============================================ || collapsive row || ============================================ */}
                      {/* {openRow[row.tenantname] && ( */}
                      {openRow === row.tenantname && (
                        <TableRow
                          sx={{
                            bgcolor:
                              openRow === row.tenantname ? "#f3e5f5" : null,
                            "&:hover": {
                              bgcolor:
                                openRow === row.tenantname
                                  ? "#f3e5f5!important"
                                  : null,
                            },
                            cursor:
                              openRow === row.tenantname ? "pointer" : null,
                          }}
                        >
                          <TableCell
                            style={{ paddingBottom: 0, paddingTop: 0 }}
                            colSpan={15}
                          >
                            <Collapse
                              // in={openRow[row.tenantname]}
                              in={true}
                              timeout="auto"
                              unmountOnExit
                            >
                              <Box sx={{ margin: 1 }}>
                                <Typography
                                  variant="h5"
                                  gutterBottom
                                  component="div"
                                >
                                  Riders Summary
                                </Typography>
                                <Table size="small" aria-label="purchases">
                                  <TableHead
                                    sx={{
                                      bgcolor: "#f3e5f5",
                                      "&:onhover": {
                                        bgcolor: "#f3e5f5!important",
                                      },
                                    }}
                                  >
                                    <TableRow>
                                      <TableCell>#</TableCell>
                                      <TableCell>Rider</TableCell>
                                      <TableCell align="left">
                                        Deliveries
                                      </TableCell>
                                      <TableCell align="left">
                                        Assigned
                                      </TableCell>
                                      <TableCell align="left">
                                        Accepted
                                      </TableCell>
                                      <TableCell align="left">Picked</TableCell>
                                      <TableCell align="left">
                                        Delivered
                                      </TableCell>
                                      <TableCell align="center">
                                        kms/actualkms
                                      </TableCell>
                                      <TableCell align="center">
                                        POD/PLA
                                      </TableCell>
                                      <TableCell align="center">
                                        Charges
                                      </TableCell>
                                    </TableRow>
                                  </TableHead>
                                  <TableBody>
                                    {ridersdata.map((row, index) => (
                                      <TableRow
                                        hover
                                        onClick={(event) =>
                                          handleClick(event, row.name)
                                        }
                                        role="checkbox"
                                        aria-checked={isItemSelected}
                                        tabIndex={-1}
                                        key={row.tenantname}
                                        selected={isItemSelected}
                                      >
                                        {/* <TableCell
                                          sx={{ pl: 3 }}
                                          padding="checkbox"
                                        >
                                          <Checkbox
                                            color="primary"
                                            checked={isItemSelected}
                                            inputProps={{
                                              "aria-labelledby": labelId,
                                            }}
                                          />
                                        </TableCell> */}
                                        <TableCell
                                          component="th"
                                          id={labelId}
                                          scope="row"
                                          padding="none"
                                        >
                                          {index + 1}
                                        </TableCell>
                                        <TableCell align="left">
                                          <Stack
                                            direction="row"
                                            sx={{ ml: -2 }}
                                          >
                                            {row.firstname}{" "}
                                            {row.status == "Active" ? (
                                              <TaskAltIcon
                                                fontSize="small"
                                                color="success"
                                                sx={{ ml: 1 }}
                                              />
                                            ) : (
                                              <HighlightOffIcon
                                                fontSize="small"
                                                color="error"
                                                sx={{ ml: 1 }}
                                              />
                                            )}{" "}
                                          </Stack>
                                        </TableCell>
                                        <TableCell align="left">
                                          {row.deliveries}
                                        </TableCell>
                                        <TableCell align="left">
                                          {row.Assigened}
                                        </TableCell>
                                        <TableCell align="left">
                                          {row.Accepted}
                                        </TableCell>
                                        <TableCell align="left">
                                          {row.Picked}
                                        </TableCell>
                                        <TableCell align="left">
                                          {row.delivered}
                                        </TableCell>
                                        <TableCell align="center">
                                          <Tooltip title="kms" placement="top">
                                            <Chip
                                              size="small"
                                              label={row.kms}
                                              sx={{
                                                color: "#1976d2",
                                                bgcolor: "#e3f2fd",
                                                mr: 1,
                                                border: "1px solid #1976d2",
                                                minWidth: 80,
                                                cursor: "pointer",
                                              }}
                                            />
                                          </Tooltip>
                                          <Tooltip
                                            title="Actual kms"
                                            placement="top"
                                          >
                                            <Chip
                                              size="small"
                                              label={row.actualkms}
                                              sx={{
                                                color: "#ff8f00",
                                                bgcolor: "#ffecb3",
                                                border: "1px solid #ff8f00",
                                                minWidth: 80,
                                                cursor: "pointer",
                                              }}
                                            />
                                          </Tooltip>
                                        </TableCell>

                                        <TableCell align="center">
                                          <Tooltip
                                            title="Pay on Delivery"
                                            placement="top"
                                          >
                                            <Chip
                                              size="small"
                                              label={formatNumberToRupees(
                                                row.payondelivery,
                                              )}
                                              sx={{
                                                color: "#f44336",
                                                bgcolor: "#ffcdd2",
                                                border: "1px solid #f44336",
                                                minWidth: 80,
                                                mr: 1,
                                                cursor: "pointer",
                                              }}
                                            />
                                          </Tooltip>
                                          <Tooltip
                                            title="Paylater"
                                            placement="top"
                                          >
                                            <Chip
                                              size="small"
                                              label={formatNumberToRupees(
                                                row.Paylater,
                                              )}
                                              sx={{
                                                color: "#43a047",
                                                bgcolor: "#c8e6c9",
                                                border: "1px solid #43a047",
                                                minWidth: 80,
                                                cursor: "pointer",
                                              }}
                                            />
                                          </Tooltip>
                                        </TableCell>

                                        <TableCell align="center">
                                          <Tooltip
                                            title="Amount"
                                            placement="top"
                                          >
                                            <Chip
                                              size="small"
                                              label={formatNumberToRupees(
                                                row.Deliveryamt,
                                              )}
                                              sx={{
                                                color: "primary.main",
                                                bgcolor: "#e1bee7",
                                                border: "1px solid #662582 ",
                                                minWidth: 100,
                                                cursor: "pointer",
                                              }}
                                            />
                                          </Tooltip>
                                        </TableCell>
                                      </TableRow>
                                    ))}
                                  </TableBody>
                                </Table>
                              </Box>
                            </Collapse>
                          </TableCell>
                        </TableRow>
                      )}
                    </>
                  ) : (
                    <TableRow>
                      <TableCell colSpan={11} rowSpan={4}>
                        <Stack
                          width={"100%"}
                          direction={"row"}
                          justifyContent={"center"}
                        >
                          <Empty />
                        </Stack>
                      </TableCell>
                    </TableRow>
                  );
                })}
              {/* {emptyRows > 0 && (
                <TableRow sx={{ height: (dense ? 33 : 53) * emptyRows }}>
                  <TableCell colSpan={6} />
                </TableRow>
              )} */}

              {/* ============================================ || 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></TableCell>
                <TableCell align="right" sx={{ pr: -2 }}>
                  <Typography variant="h5">
                    {formatNumberToRupees(total)}
                  </Typography>
                </TableCell>{" "}
                <TableCell></TableCell>
              </TableRow>
            </TableBody>
          </Table>
        </TableContainer>
        <Divider />

        {/* table pagination */}
        {/* <TablePagination
          rowsPerPageOptions={[5, 10, 25]}
          component="div"
          count={rows.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        /> */}
      </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") {
                setDateselect("all");
                setStartdate("");
                setEnddate("");

                setOpen(false);
              } else {
                setDateselect("select");
                setStartdate(dayjs(range.startDate).format("YYYY-MM-DD"));
                setEnddate(dayjs(range.endDate).format("YYYY-MM-DD"));
                if (range.label) {
                  setDatestatus(range.label);
                } else {
                  setDatestatus("");
                }
              }
              console.log(range);
            }}
            definedRanges={[
              {
                label: "Today",
                startDate: new Date(),
                endDate: new Date(),
              },
              {
                label: "Yesterday",
                startDate: addDays(new Date(), -1),
                endDate: addDays(new Date(), -1),
              },
              {
                label: "Tomorrow",
                startDate: addDays(new Date(), +1),
                endDate: addDays(new Date(), +1),
              },
              {
                label: "This Week",
                startDate: startOfWeek(new Date()),
                endDate: endOfWeek(new Date()),
              },
              {
                label: "Last Week",
                startDate: startOfWeek(addWeeks(new Date(), -1)),
                endDate: endOfWeek(addWeeks(new Date(), -1)),
              },
              {
                label: "Last 7 Days",
                startDate: addWeeks(new Date(), -1),
                endDate: new Date(),
              },
              {
                label: "This Month",
                startDate: startOfMonth(new Date()),
                endDate: endOfMonth(new Date()),
              },
              {
                label: "Last Month",
                startDate: startOfMonth(addMonths(new Date(), -1)),
                endDate: endOfMonth(addMonths(new Date(), -1)),
              },
              {
                label: "All",
                startDate: new Date(),
                endDate: addDays(new Date(), -1),
              },
            ]}
          />
        </DialogContent>
        <Stack
          direction="row"
          justifyContent="flex-end"
          sx={{ width: "100%", p: 2 }}
        >
          <Button
            variant="contained"
            size="small"
            onClick={() => setOpen(false)}
          >
            ok
          </Button>
        </Stack>
      </Dialog>
    </>
  );
}
