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 ClearIcon from "@mui/icons-material/Clear";
import { useTheme } from "@mui/material/styles";
// import firebase from "../../firebase/firebase";
import MapWithRoute from "./mapWithRoute";
import { SlLocationPin } from "react-icons/sl";
import CloseOutlinedIcon from "@mui/icons-material/CloseOutlined";
import DisabledByDefaultOutlinedIcon from "@mui/icons-material/DisabledByDefaultOutlined";
import { FaRegCheckCircle } from "react-icons/fa";
import { FaCircleCheck } from "react-icons/fa6";

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

// project imports
import {
  fetchorderdetails,
  fetchCount,
  fetchAppLocations,
} from "pages/api/api";
import MainCard from "components/MainCard";
import {
  CSVExport,
  TableRowSelection,
} from "components/third-party/ReactTable";
import Loader from "components/Loader";
import { enqueueSnackbar } from "notistack";

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

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);
}
const headCells = [
  {
    id: "sno",
    disablePadding: false,
    label: "#",
  },
  {
    id: "map",
    disablePadding: false,
    label: "^",
  },
  {
    id: "tenantname",
    disablePadding: false,
    label: "Client",
  },

  {
    id: "Pickup loco",
    disablePadding: false,
    label: "Pickup",
  },
  {
    id: "Delivery loco",
    disablePadding: false,
    label: "Drop",
  },
  {
    id: "order status",
    disablePadding: false,
    label: "status",
  },
  {
    id: "assigned",
    disablePadding: false,
    label: "assigned",
  },
  {
    id: "Accepted",
    disablePadding: false,
    label: "Accepted",
  },
  {
    id: "arrived",
    disablePadding: false,
    label: "arrived",
  },
  {
    id: "picked",
    disablePadding: false,
    label: "picked",
  },

  {
    id: "Delivered",
    disablePadding: false,
    label: "Delivered",
  },
  {
    id: "cancelled",
    disablePadding: false,
    label: "cancelled",
  },

  {
    id: " notes",
    disablePadding: false,
    label: "NOTES",
  },

  {
    id: "kms",
    disablePadding: false,
    label: "KMS",
    numeric: "center",
  },

  {
    id: "charges",
    numeric: "center",
    label: "Charges",
    disablePadding: false,
  },
];

// ==============================|| 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"
                : headCell.numeric === "left"
                ? "left"
                : "right"
            }
            padding={headCell.disablePadding ? "none" : "normal"}
            sortDirection={orderBy === headCell.id ? order : undefined}
          >
            <TableSortLabel
              active={orderBy === headCell.id}
              direction={orderBy === headCell.id ? order : "asc"}
              onClick={createSortHandler(headCell.id)}
            >
              {headCell.label}
              {orderBy === headCell.id ? (
                <Box component="span" sx={visuallyHidden}>
                  {order === "desc" ? "sorted descending" : "sorted ascending"}
                </Box>
              ) : null}
            </TableSortLabel>
          </TableCell>
        ))}
      </TableRow>
    </TableHead>
  );
}

// ==============================|| MUI TABLE - ENHANCED ||============================== //
const tabContent = ["Delivered", "Pending", "Cancelled"];

export default function ordersDetails() {
  const theme = useTheme();
  const userid = localStorage.getItem("ne-userid");

  const [rows, setRows] = useState([]);
  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(10);
  const [selectedValue, setSelectedValue] = useState([]);
  const [locaName, setLocoName] = useState("All");
  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 [dateselect, setDateselect] = useState("select");
  const [tabstatus1, setTabstatus1] = useState("Today");
  const [datestatus, setDatestatus] = useState("Today");
  const [totalCharge, settotalCharge] = useState(0);
  const [totalAmount, settotalAmount] = useState(0);
  const [appId, setAppId] = useState(0);
  const [value, setValue] = useState(0);
  const [tabvalue, setTabvalue] = useState(0);
  const [tabstatus, setTabstatus] = useState("Delivered");
  const [deliCount, setDeliCount] = useState(0);
  const [pendCount, setPendCount] = useState(0);
  const [cancelCount, setCancelCount] = useState(0);
  const [searchword, setSearchword] = useState("");
  const [count, setCount] = useState(0);
  const [users, setUsers] = useState([]);
  const [riderCoordinates, setRiderCoordinates] = useState([]);
  const [riderStart, setRiderStart] = useState();
  const [riderEnd, setRiderEnd] = useState();
  const [riderkms, setRiderKms] = useState();
  const [mapTenant, setMapTenant] = useState({});
  const [isLoading, setIsLoading] = useState(false);

  let [total, settotal] = useState(0);
  let [coveredLenght, setCoveredLenght] = useState(0);
  let [uncoveredLenght, setUncoveredLenght] = useState(0);
  let [cancelLenght, setCancelLenght] = useState(0);
  let [assignLenght, setAssignLenght] = useState(0);
  let [pickedLenght, setPickedLenght] = useState(0);
  let [activeLenght, setActiveLenght] = useState(0);
  let [arrivesLenght, setArrivedLenght] = useState(0);
  const [statusCount, setStatusCount] = useState();
  const [currentStatus, setCurrentStatus] = useState("All");

  const status = [
    { id: 0, status: "All", statusLow: "All", count: total },
    { id: 1, status: "Pending", statusLow: "pending", count: assignLenght },
    {
      id: 2,
      status: "Accepted",
      statusLow: "accepted",
      count: uncoveredLenght,
    },
    { id: 3, status: "Arrived", statusLow: "arrived", count: arrivesLenght },
    { id: 4, status: "Picked", statusLow: "picked", count: pickedLenght },
    { id: 5, status: "Active", statusLow: "active", count: activeLenght },
    {
      id: 6,
      status: "Delivered",
      statusLow: "delivered",
      count: coveredLenght,
    },
    { id: 7, status: "Cancelled", statusLow: "cancelled", count: cancelLenght },
  ];

  const handleChangetab = (e, i) => {
    setTabvalue(i);
    if (i === 0) {
      setCurrentStatus("pending");
    }
    if (i === 1) {
      setCurrentStatus("accepted");
    }
    if (i === 2) {
      setCurrentStatus("arrived");
    }
    if (i === 3) {
      setCurrentStatus("picked");
    }
    if (i === 4) {
      setCurrentStatus("active");
    }
    if (i === 5) {
      setCurrentStatus("delivered");
    }
    if (i === 6) {
      setCurrentStatus("cancelled");
      1;
    }
    console.log(i);
    setSearchword("");
  };

  const textFieldRef = useRef(null);

  const handleButtonClick = (clickedOrderId) => {
    console.log("clickedOrderId", clickedOrderId);
    const filteredUsers = users.filter(
      (user) => user.orderid === clickedOrderId
    );
    console.log("Filtered firebasedata:", filteredUsers);
    console.log("Coordinates:", filteredUsers);
  };

  // Function to calculate distance between two coordinates using Haversine formula
  function calculateDistance(lat1, lon1, lat2, lon2) {
    const R = 6371; // Radius of the Earth in kilometers
    const dLat = (lat2 - lat1) * (Math.PI / 180);
    const dLon = (lon2 - lon1) * (Math.PI / 180);
    const a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(lat1 * (Math.PI / 180)) *
        Math.cos(lat2 * (Math.PI / 180)) *
        Math.sin(dLon / 2) *
        Math.sin(dLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const distance = R * c; // Distance in kilometers
    return distance;
  }

  // Function to calculate total distance traveled along the route
  function calculateTotalDistance(routeCoordinates) {
    let totalDistance = 0;
    for (let i = 0; i < routeCoordinates.length - 1; i++) {
      const { lat: lat1, lng: lon1 } = routeCoordinates[i];
      const { lat: lat2, lng: lon2 } = routeCoordinates[i + 1];
      const distance = calculateDistance(lat1, lon1, lat2, lon2);
      console.log("distance", distance);
      totalDistance += distance;
    }
    return totalDistance;
  }

  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);
        const totalDistance = calculateTotalDistance(coData);
        setRiderKms(totalDistance);
        console.log("Total distance traveled:", totalDistance, "km");

        setOpen1(true);
      } else {
        opentoast("No Logs Found ", "error", 2000);
      }
    } catch (error) {
      console.log("getdeliverylogs", error);
    }
  };

  /* ============================================= || 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);
    };
  }, []);
  // ==============================|| fetchorderdetails (orders)||============================== //
  const fetchorderdetails = async () => {
    setIsLoading(true);
    try {
      const response = await axios.get(
        appId == 0
          ? currentStatus == "All"
            ? `${
                process.env.REACT_APP_URL2
              }/deliveries/getdeliveries/?fromdate=${startdate}&todate=${enddate}&pageno=${
                page + 1
              }&pagesize=${rowsPerPage}`
            : `${
                process.env.REACT_APP_URL2
              }/deliveries/getdeliveries/?fromdate=${startdate}&todate=${enddate}&status=${currentStatus}&pageno=${
                page + 1
              }&pagesize=${rowsPerPage}`
          : currentStatus == "All"
          ? `${
              process.env.REACT_APP_URL2
            }/deliveries/getdeliveries/?fromdate=${startdate}&todate=${enddate}&applocationid=${appId}&pageno=${
              page + 1
            }&pagesize=${rowsPerPage}`
          : `${
              process.env.REACT_APP_URL2
            }/deliveries/getdeliveries/?fromdate=${startdate}&todate=${enddate}&applocationid=${appId}&status=${currentStatus}&pageno=${
              page + 1
            }&pagesize=${rowsPerPage}`
      );
      const detailsWithSNo = response.data.details.map((item, index) => ({
        ...item,
        sno: index + 1,
      }));
      setRows(detailsWithSNo);
      setIsLoading(false);
    } catch (error) {
      console.log("fetchorderdetails", error.message);
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchorderdetails();
  }, [tabvalue, appId, startdate, enddate, page, rowsPerPage, currentStatus]);

  // ==============================|| calculate||============================== //
  const calculate = () => {
    let calculatedTotalCharge = 0;
    let calculatedTotalAmount = 0;
    rows &&
      rows.forEach((row) => {
        calculatedTotalCharge += row.deliverycharge;
      });
    settotalCharge(calculatedTotalCharge);
    rows &&
      rows.forEach((row) => {
        calculatedTotalAmount += row.deliveryamt;
      });
    console.log("calculatedTotalAmount", calculatedTotalAmount);
    settotalAmount(calculatedTotalAmount);
  };
  // useEffect(() => {
  //   calculate();
  //   rows && setRowsPerPage(rows.length + 1);
  //   rows && setCount(rows.length);
  // }, [rows]);

  /* ============================================= || fetchcount | ============================================= */
  const fetchcount = async () => {
    try {
      await axios
        .get(
          appId == 0
            ? `${process.env.REACT_APP_URL}/deliveries/deliverysummary/?fromdate=${startdate}&todate=${enddate}`
            : `${process.env.REACT_APP_URL}/deliveries/deliverysummary/?applocationid=${appId}&fromdate=${startdate}&todate=${enddate}`
        )
        .then((res) => {
          console.log("fetchcountres", res.data.details);

          settotal(res.data.details.total);
          setStatusCount(res.data.details.total);
          setUncoveredLenght(res.data.details.pending);
          setAssignLenght(res.data.details.accepted);
          setArrivedLenght(res.data.details.arrived);
          setPickedLenght(res.data.details.picked);
          setActiveLenght(res.data.details.active);
          setCoveredLenght(res.data.details.delivered);
          setCancelLenght(res.data.details.cancelled);
        })
        .catch((err) => {
          console.log(err);
          enqueueSnackbar(err.message, {
            variant: "error",
            anchorOrigin: { vertical: "top", horizontal: "right" },
            autoHideDuration: 2000,
          });
        });
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(() => {
    fetchcount();
  }, [appId, startdate, enddate]);
  // ==============================|| fetchAppLocations ||============================== //
  const {
    isLoading: isLoadingLocations,
    isError: isErrorLocations, //true or false
    data: locations,
    error: locationsError,
  } = useQuery({
    queryKey: [],
    queryFn: fetchAppLocations,
  });
  if (isLoadingLocations) return <Loader />;
  if (isErrorLocations)
    return "An error has occurred:(isErrorlocations) " + locationsError.message;

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

  // ==============================|| filteredOrders ||============================== //

  const filteredOrders = rows.filter(
    (row) =>
      row.orderid.includes(searchword) ||
      row.tenantname.toLowerCase().includes(searchword.toLowerCase()) ||
      row.pickupcustomer.toLowerCase().includes(searchword.toLowerCase()) ||
      row.pickupcontactno.toLowerCase().includes(searchword.toLowerCase()) ||
      row.deliverycustomer.toLowerCase().includes(searchword.toLowerCase()) ||
      row.ridername.toLowerCase().includes(searchword.toLowerCase()) ||
      row.deliverycontactno.includes(searchword.toLowerCase())
  );

  // to download ex format filtered data
  const csvData = filteredOrders.map((order) => ({
    tenantname: order.tenantname,
    tenantcity: order.tenantcity,
    tenantcontactno: order.tenantcontactno,
    rider: order.ridername,
    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,
  }));
  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));
  };

  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;

  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;
  }
  return (
    <>
      {isLoading && <Loader />}
      <TitleCard title="Orders Details" />{" "}
      <Paper
        content={false}
        sx={{ border: "1px solid #eeeeee", borderBottom: "none", mt: "10px" }}
      >
        {" "}
        <Grid container sx={{ display: "flex", alignItems: "center", m: 2 }}>
          <Grid item xs={4}>
            {" "}
            <Stack direction="column" alignItems="flex-start" spacing={1}>
              {startdate && enddate && (
                <Stack direction="row" spacing={2}>
                  <Badge
                    badgeContent={`${statusCount}`}
                    max={`${total}`}
                    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"
                  />
                </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>
          </Grid>
          <Grid item xs={8}>
            <div
              style={{
                display: "flex",
                flexDirection: "row",
                justifyContent: "end",
                marginRight: "25px",
              }}
            >
              <FormControl
                sx={{ width: 250, display: { xs: "none", md: "flex" } }}
              >
                <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("");
                        // setPages(1);
                        // fetchCustomersList(1);
                      }}
                    >
                      <ClearIcon
                        style={{ fontSize: "medium", color: "#65387A" }}
                      />
                    </IconButton>
                  }
                />
              </FormControl>
              <Autocomplete
                disablePortal
                id="combo-box-demo"
                label={currentStatus}
                options={status}
                getOptionLabel={(option) => `${option.status}`}
                sx={{ width: 300, height: "30px", ml: 3, zIndex: "100" }}
                onChange={(event, value, reason) => {
                  if (reason === "clear") {
                    setCurrentStatus("All");
                    setStatusCount(status[0].count);
                  } else {
                    console.log("status", value);
                    setCurrentStatus(value.statusLow);
                    setStatusCount(value.count);
                  }
                }}
                renderInput={(params) => (
                  <TextField {...params} label={"Select Status"} />
                )}
              />
              <Autocomplete
                disablePortal
                id="combo-box-demo"
                label={locaName}
                options={locations}
                getOptionLabel={(option) => `${option.locationname}`}
                sx={{ width: 300, height: "30px", ml: 3, zIndex: "100" }}
                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={"Select Location"} />
                )}
              />
              <Tooltip title="Order Filter">
                <IconButton
                  // size='large'

                  color="secondary"
                  variant="light"
                  sx={{
                    color: "text.primary",
                    bgcolor: "grey.200",
                    display: { xs: "none", md: "flex" },
                    ml: 2,
                    mr: 2,
                  }}
                  // aria-label="open profile"
                  // ref={anchorRef}
                  // aria-controls={open ? 'profile-grow' : undefined}
                  aria-haspopup="true"
                  // onClick={handleToggle}

                  onClick={() => setOpen(true)}
                >
                  <FilterList />
                </IconButton>
              </Tooltip>
              <CSVExport
                data={csvData}
                filename={`Orders_Detail_${dayjs().format(
                  "YYYY-MM-DD_HHmmss"
                )}.csv`}
              />
            </div>
          </Grid>
        </Grid>
      </Paper>
      <MainCard content={false}>
        <TableContainer
          sx={{
            minHeight: "auto",
            maxHeight: "67vh",
            overflow: "auto",
            "&::-webkit-scrollbar": {
              width: "2px", // Width of vertical scrollbar
              height: "2px", // Height of horizontal scrollbar
            },
            "&::-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>
                {headCells.map((column) => (
                  <TableCell
                    sx={{ position: "sticky !important" }}
                    key={column.id}
                  >
                    {column.label}
                  </TableCell>
                ))}
              </TableRow>
            </TableHead>
            <TableBody>
              {filteredOrders.lenght == 0 ? (
                <TableRow>
                  <TableCell colSpan={3} rowSpan={14}>
                    <Empty />
                  </TableCell>
                </TableRow>
              ) : (
                filteredOrders.map((row, index) => {
                  const isItemSelected = isSelected(row.name);
                  return (
                    <TableRow
                      hover
                      // onClick={(event) =>
                      //   handleClick(event, row.name)
                      // }
                      role="checkbox"
                      aria-checked={isItemSelected}
                      tabIndex={-1}
                      key={row.name}
                      selected={isItemSelected}
                    >
                      {/* <TableCell sx={{ pl: 3 }} padding="checkbox">
                                    <Checkbox
                                      color="primary"
                                      checked={isItemSelected}
                                      inputProps={{
                                        "aria-labelledby": labelId,
                                      }}
                                    />
                                  </TableCell> */}
                      <TableCell sx={{ width: "10px" }}>{row.sno}</TableCell>
                      <TableCell
                        sx={{ width: "10px", cursor: "pointer" }}
                        onClick={() => {
                          console.log("row", row);
                          getdeliverylogs(row.deliveryid);
                          setMapTenant(row);
                          setIsLoading(true);
                          setTimeout(() => {
                            setIsLoading(false);
                          }, 500);
                        }}
                      >
                        {<SlLocationPin />}
                      </TableCell>

                      <TableCell
                        sx={{
                          textAlign: "start",
                          minWidth: 150,
                        }}
                      >
                        {row.tenantname}
                        <Tooltip title={"OrderId"}>
                          <Typography
                            variant="body2"
                            noWrap
                            sx={{ cursor: "pointer" }}
                          >
                            {row.orderid}
                          </Typography>
                        </Tooltip>
                        <Typography noWrap sx={{ fontSize: "11px" }}>
                          {dayjs(row.deliverydate).utc().format("DD/MM/YYYY")}
                        </Typography>
                        <Typography
                          noWrap
                          sx={{ fontSize: "11px" }}
                          variant="h5"
                        >
                          {dayjs(row.deliverydate).utc().format("hh:mm A")}
                        </Typography>
                      </TableCell>
                      <TableCell align="left">
                        <Stack direction={"row"} spacing={1}>
                          <Stack direction="column">
                            <Typography variant="caption">
                              {row.pickupcustomer}
                            </Typography>
                            <Typography variant="caption" color="textSecondary">
                              {row.pickupcontactno}
                            </Typography>
                            <Tooltip title={row.pickupaddress}>
                              <Typography
                                variant="caption"
                                color="textSecondary"
                                sx={{ cursor: "pointer" }}
                              >
                                {row.pickupsuburb ||
                                  row.Pickupaddress.slice(0, 20)}
                              </Typography>
                            </Tooltip>
                            <Typography
                              noWrap
                              sx={{ fontSize: "11px" }}
                              variant="h5"
                            >
                              {row.applocation}
                            </Typography>
                          </Stack>
                        </Stack>
                      </TableCell>
                      <TableCell align="left">
                        <Stack direction={"row"} spacing={1}>
                          <Stack direction="column">
                            <Typography variant="caption">
                              {row.deliverycustomer}
                            </Typography>
                            <Typography variant="caption" color="textSecondary">
                              {row.deliverycontactno}
                            </Typography>
                            <Tooltip title={row.deliveryaddress}>
                              <Typography
                                variant="caption"
                                color="textSecondary"
                                sx={{ cursor: "pointer" }}
                              >
                                {/* {row.pickupaddress.slice(0, 20)} */}
                                {row.deliverysuburb ||
                                  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 === "cancelled" && (
                            <Chip
                              label="Cancelled"
                              color="error"
                              size="small"
                              sx={{ minWidth: 80 }}
                            />
                          )}
                        </Stack>
                      </TableCell>

                      <TableCell align="left">
                        <Tooltip title={`Rider-(${row.ridername})`}>
                          <Typography
                            variant="caption"
                            display="block"
                            sx={{ cursor: "pointer" }}
                          >
                            {row.ridername
                              ? `${row.ridername.slice(0, 5)}...`
                              : null}
                          </Typography>
                        </Tooltip>
                        <Typography noWrap sx={{ fontSize: "11px" }}>
                          {/* {dayjs(row.pending).format('DD/MM/YYYY')} */}
                          {row.assigntime === ""
                            ? ""
                            : formatDate(row.assigntime)}
                        </Typography>
                        <Typography
                          noWrap
                          sx={{ fontSize: "11px" }}
                          variant="h5"
                        >
                          {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>
                        <Stack direction={"row"}>
                          <Typography
                            noWrap
                            sx={{ fontSize: "11px" }}
                            variant="h5"
                          >
                            {row.pickuptime === ""
                              ? ""
                              : formatTime(row.pickuptime)}
                          </Typography>
                          {row.deliverystatus === "active" && (
                            <FaCircleCheck
                              fontSize={"large"}
                              style={{ color: "green", marginLeft: "8px" }}
                            />
                          )}
                        </Stack>
                      </TableCell>
                      {/* <TableCell align="left">
                          {' '}
                          {row.activetime ? (
                            <Typography noWrap sx={{ fontSize: '11px' }}>
                              row.activetime === '' ? '' : formatDate(row.activetime)
                            </Typography>
                          ) : null}
                          {row.activetime ? (
                            <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                              row.activetime === '' ? '' : formatTime(row.activetime)
                            </Typography>
                          ) : null}
                        </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">
                          <Typography variant="caption">
                            {row.rider ? (
                              <>
                                {row.rider.substring(0, 1).toUpperCase() + row.rider.substring(1, 8).toLowerCase()} <br />
                                {row.rider.substring(8).toLowerCase()}
                              </>
                            ) : (
                              row.rider
                            )}
                          </Typography>
                        </TableCell> */}

                      <TableCell align="center">
                        <Stack direction={"column"} spacing={1}>
                          <Tooltip title=" KMS" placement="top">
                            <Chip
                              label={
                                row.deliverystatus === "cancelled" ||
                                row.kms == ""
                                  ? 0
                                  : row.kms
                              }
                              size="small"
                              variant="light"
                              color="error"
                              sx={{
                                minWidth: 80,
                                border: "1px solid  #e96969",
                                cursor: "pointer",
                              }}
                            />
                          </Tooltip>
                          <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"
                              onClick={() => {
                                // handleButtonClick(row.orderid);
                                // getdeliverylogs(row.deliveryid);
                              }}
                              sx={{
                                minWidth: 80,
                                border: "1px solid #76ff03 ",
                                cursor: "pointer",
                              }}
                            />
                          </Tooltip>
                          <Tooltip title="Rider KMS">
                            <Chip
                              label={
                                row.deliverystatus === "cancelled" ||
                                row.riderkms === "" ||
                                row.riderkms === "null"
                                  ? "0.0"
                                  : // : parseFloat(row.actualkms).toFixed(2)
                                    row.riderkms
                              }
                              size="small"
                              color="info"
                              variant="light"
                              onClick={() => {
                                // handleButtonClick(row.orderid);
                                // getdeliverylogs(row.deliveryid);
                              }}
                              sx={{
                                minWidth: 80,
                                border: "1px solid #03a9f4 ",
                                cursor: "pointer",
                              }}
                            />
                          </Tooltip>
                        </Stack>
                      </TableCell>

                      <TableCell align="center">
                        <Stack direction={"column"} spacing={1}>
                          <Tooltip title=" Delivery Charge" placement="top">
                            <Chip
                              label={
                                row.orderstatus === "cancelled" ||
                                row.deliverycharges == ""
                                  ? `₹ ${0}.00`
                                  : `₹ ${row.deliverycharges}.00`
                              }
                              size="small"
                              variant="light"
                              color="error"
                              sx={{
                                minWidth: 80,
                                border: "1px solid  #e96969",
                                cursor: "pointer",
                              }}
                            />
                          </Tooltip>
                          <Tooltip title="Delivery Amount">
                            <Chip
                              label={
                                row.deliveryamt == ""
                                  ? `₹ ${0}.00`
                                  : `₹ ${row.deliveryamt}.00`
                              }
                              size="small"
                              color="success"
                              variant="light"
                              sx={{
                                minWidth: 80,
                                border: "1px solid #76ff03 ",
                                cursor: "pointer",
                              }}
                            />
                          </Tooltip>
                        </Stack>
                      </TableCell>
                    </TableRow>
                  );
                })
              )}
            </TableBody>
          </Table>
        </TableContainer>
        <Divider />
        {/* table pagination */}
        <TablePagination
          rowsPerPageOptions={[10, 25, 100, `${statusCount}`]}
          component="div"
          count={statusCount}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        />
        {/* <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> */}
      </MainCard>{" "}
      {/* Date picker 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>
      <Dialog
        open={open1}
        onClose={() => {
          setOpen1(false);
        }}
        maxWidth={"lg"}
        fullWidth
      >
        <DialogTitle
          sx={{
            // bgcolor: '#eee',

            display: "flex",
            flexDirection: "row",
            justifyContent: "space-between",
            alignItems: "center",
            mx: 3.5,
          }}
        >
          <Stack direction={"row"} spacing={2}>
            <Stack
              direction={"column"}
              spacing={1}
              alignItems={"start"}
              justifyContent={"start"}
            >
              <Stack direction={"row"} spacing={2} alignItems={"center"}>
                <Typography variant="h6" sx={{ width: "50px" }}>
                  Tenant:
                </Typography>{" "}
                <Chip
                  size="small"
                  color="secondary"
                  label={mapTenant?.tenantname}
                />
              </Stack>
              <Stack direction={"row"} spacing={2} alignItems={"center"}>
                <Typography variant="h6" sx={{ width: "50px" }}>
                  Rider:
                </Typography>{" "}
                <Chip
                  size="small"
                  color="secondary"
                  label={mapTenant?.ridername}
                />
              </Stack>
            </Stack>

            <Stack
              direction={"column"}
              spacing={1}
              alignItems={"start"}
              justifyContent={"start"}
            >
              <Stack direction={"row"} spacing={2} alignItems={"center"}>
                <Typography variant="h6" sx={{ width: "50px" }}>
                  Pickup:
                </Typography>
                <Chip
                  size="small"
                  color="secondary"
                  label={mapTenant?.pickupcustomer}
                />
              </Stack>
              <Stack direction={"row"} spacing={2} alignItems={"center"}>
                <Typography variant="h6" sx={{ width: "50px" }}>
                  Drop:{"  "}
                </Typography>
                <Chip
                  size="small"
                  color="secondary"
                  label={mapTenant?.deliverycustomer}
                />
              </Stack>
            </Stack>

            <Stack
              direction={"column"}
              spacing={1}
              alignItems={"start"}
              justifyContent={"start"}
            >
              <Stack direction={"row"} spacing={2} alignItems={"center"}>
                <Typography variant="h6" sx={{ width: "100px" }}>
                  Kms:
                </Typography>{" "}
                <Chip
                  size="small"
                  color="secondary"
                  label={`${mapTenant?.kms} kms`}
                />
              </Stack>
              <Stack direction={"row"} spacing={2} alignItems={"center"}>
                <Typography variant="h6" sx={{ width: "100px" }}>
                  Actual kms:
                </Typography>{" "}
                <Chip
                  size="small"
                  color="secondary"
                  label={`${mapTenant?.actualkms} kms`}
                />
              </Stack>
            </Stack>

            <Stack
              direction={"column"}
              spacing={1}
              alignItems={"start"}
              justifyContent={"start"}
            >
              <Stack direction={"row"} spacing={2} alignItems={"center"}>
                <Typography variant="h6" sx={{ width: "100px" }}>
                  Rider kms:
                </Typography>{" "}
                <Chip
                  size="small"
                  color="secondary"
                  label={`${mapTenant?.riderkms} kms`}
                />
              </Stack>
            </Stack>
          </Stack>

          <DisabledByDefaultOutlinedIcon
            sx={{ color: theme.palette.error.main, cursor: "pointer", ml: 2 }}
            fontSize="large"
            onClick={() => {
              setOpen1(false);
            }}
          />
        </DialogTitle>
        <DialogContent>
          {riderCoordinates && (
            <div>
              <MapWithRoute
                coordinates={riderCoordinates}
                additionalProps={{ riderStart, riderEnd }}
              />
            </div>
          )}
        </DialogContent>
      </Dialog>
    </>
  );
}
