import * as React from "react";
import Loader from "components/Loader";
import { useState, Fragment, useRef } from "react";
import { usePlacesWidget } from "react-google-autocomplete";
import Autocomplete from "react-google-autocomplete";
import { Autocomplete as Autocomplete1 } from "@mui/material";
import Geocode from "react-geocode";
import { Link as RouterLink, useNavigate } from "react-router-dom";
import { DeleteFilled, NotificationOutlined } from "@ant-design/icons";
import ClearIcon from "@mui/icons-material/Clear";
import { Empty } from "antd";
import {
  AimOutlined,
  EnvironmentOutlined,
  MailOutlined,
  PhoneOutlined,
} from "@ant-design/icons";
import {
  Avatar,
  Button,
  Box,
  Grid,
  Skeleton,
  Stack,
  Chip,
  Typography,
  Divider,
  Table,
  TableCell,
  TableBody,
  TableHead,
  IconButton,
  Collapse,
  Tabs,
  Tab,
  Dialog,
  DialogActions,
  DialogTitle,
  DialogContent,
  CircularProgress,
  TableSortLabel,
  TableRow,
  List,
  ListItem,
  ListItemIcon,
  FormControl,
  OutlinedInput,
  InputAdornment,
  Popper,
  ClickAwayListener,
  InputLabel,
  TextField,
  Select,
  MenuItem,
  Link,
  Tooltip,
  Badge,
  ListItemSecondaryAction,
  useMediaQuery,
} from "@mui/material";
import { PatternFormat } from "react-number-format";

// import { PopupTransition } from 'components/@extended/Transitions';
import { SearchOutlined } from "@ant-design/icons";
import { enqueueSnackbar } from "notistack";
var utc = require("dayjs/plugin/utc");
import axios from "axios";
import { useTheme } from "@mui/material/styles";
import { MoreOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
dayjs.extend(utc);
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
import PropTypes from "prop-types";
import TableContainer from "@mui/material/TableContainer";
import TablePagination from "@mui/material/TablePagination";
import { visuallyHidden } from "@mui/utils";
import { useEffect } from "react";
import MainCard from "components/MainCard";

const Riders = () => {
  const navigate = useNavigate();
  let theme = useTheme();
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(false);

  const [searchword, setSearchword] = useState("");
  const [stafflist, setStafflist] = useState([]);
  const textFieldRef = useRef(null);

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

  useEffect(() => {
    if (searchword) {
      let arr = stafflist.filter((val) => {
        return (
          val.firstname.toLowerCase().includes(searchword.toLowerCase()) ||
          // || val.locationaddress.toLowerCase().includes(searchword.toLowerCase())
          val.contactno.toLowerCase().includes(searchword.toLowerCase()) ||
          // || val.email.toString().toLowerCase().includes(searchword.toLowerCase())
          val.address
            .toString()
            .toLowerCase()
            .includes(searchword.toLowerCase())
          // || val.staffname.toString().toLowerCase().includes(searchword.toLowerCase())
        );
      });
      console.log(arr);
      setRows([...arr]);
    } else {
      setRows([...stafflist]);
    }
    // console.log(searchword)
  }, [searchword]);

  const fetchtable = async (tid) => {
    setLoading(true);
    try {
      await axios
        .get(`${process.env.REACT_APP_URL}/partners/getallriders`)

        .then((res) => {
          if (res.data.status) {
            let arr = [];
            res.data.details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            setRows([...arr]);
            setStafflist([...arr]);
            console.log("getallriders", arr);
            setLoading(false);
          }
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
          enqueueSnackbar(err.message, {
            variant: "error",
            anchorOrigin: { vertical: "top", horizontal: "right" },
            autoHideDuration: 2000,
          });
        });
    } catch (err) {
      console.log(err);
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchtable();
  }, []);

  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);
  }

  // Since 2020 all major browsers ensure sort stability with Array.prototype.sort().
  // stableSort() brings sort stability to non-modern browsers (notably IE11). If you
  // only support modern browsers you can replace stableSort(exampleArray, exampleComparator)
  // with exampleArray.slice().sort(exampleComparator)

  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]);
  }

  const headCells = [
    {
      id: "sno",
      disablePadding: true,
      label: "#",
    },
    {
      id: "tenantname",
      numeric: false,
      disablePadding: false,
      label: "Rider",
    },

    {
      id: "address",
      numeric: false,
      disablePadding: false,
      label: "ADDRESS",
    },

    {
      id: "vehicle",
      disablePadding: false,
      label: "Vehicle",
    },
    {
      id: "eventname",
      disablePadding: false,
      label: "SHIFT",
    },

    {
      id: "endtime",
      disablePadding: false,
      label: "Time",
    },

    {
      id: "orderstatus",
      disablePadding: false,
      label: "Fare",
    },

    {
      id: "orderstatus6",
      disablePadding: false,
      label: "Fuel",
    },

    {
      id: "orderstatus",
      disablePadding: false,
      label: "STATUS",
    },

    {
      id: "orderstatus1",
      disablePadding: false,
      label: "ACTION",
    },
  ];

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

    return (
      <TableHead>
        <TableRow>
          {/* <TableCell padding="checkbox">
                        <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 ? "right" : "left"}
              padding={headCell.disablePadding ? "none" : "normal"}
              sortDirection={orderBy === headCell.id ? order : false}
            >
              <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>
    );
  }

  function EnhancedTable() {
    const [order, setOrder] = React.useState("asc");
    const [orderBy, setOrderBy] = React.useState("calories");
    const [selected, setSelected] = React.useState([]);
    const [page, setPage] = React.useState(0);
    //   const [dense, setDense] = React.useState(false);
    const [rowsPerPage, setRowsPerPage] = React.useState(10);
    const [expandopen, setExpandopen] = useState("");
    const [open, setOpen] = useState("");
    const [loading1, setLoading1] = useState(false);
    const [staffdetaillist, setStaffdetaillist] = useState([]);
    const [anchorEl, setAnchorEl] = React.useState(null);
    const [currentcustomerid, setCurrentcustomerid] = useState("");
    const [businessname, setBusinessname] = useState("");
    const [businessno, setBusinessno] = useState("");
    const [mobilenumber, setMobilenumber] = useState("");
    const [emailaddress, setEmailaddress] = useState("");
    const [city, setCity] = useState("");
    const [zipcode, setZipcode] = useState("");
    const [address, setAddress] = useState("");
    const [state, setState] = useState("");
    const [suburb, setSuburb] = useState("");
    const [latlong, setLatlong] = useState({});
    const [profiledetails, setProfiledetails] = useState({});
    const [primarycontact, setPrimarycontact] = useState("");
    const [firstname, setFirstname] = useState("");
    const [doorno, setDoorno] = useState("");
    const [landmark, setLandmark] = useState("");
    const [tenantinfo, setTenantinfo] = useState({});
    Geocode.setApiKey(process.env.REACT_APP_GOOGLE_MAPS_API_KEY);
    const [open2, setOpen2] = useState("");
    const [openRow, setOpenRow] = useState(null); // Initially no row is open  const [searchword, setSearchword] = useState('');
    const textFieldRef = useRef(null);
    const matchDownMD = useMediaQuery((theme) => theme.breakpoints.down("md"));
    const [riderdata, setRiderdata] = useState({});
    const [value, setValue] = React.useState(0);

    function CustomTabPanel(props) {
      const { children, value, index, ...other } = props;

      return (
        <div
          role="tabpanel"
          hidden={value !== index}
          id={`simple-tabpanel-${index}`}
          aria-labelledby={`simple-tab-${index}`}
          {...other}
        >
          {value === index && (
            <Box sx={{}}>
              <Typography>{children}</Typography>
            </Box>
          )}
        </div>
      );
    }

    function a11yProps(index) {
      return {
        id: `simple-tab-${index}`,
        "aria-controls": `simple-tabpanel-${index}`,
      };
    }

    const handleChange = (event, newValue) => {
      setValue(newValue);
    };

    const fetchRiderData = async (id) => {
      try {
        let riderdataresponse = await axios.get(
          `${process.env.REACT_APP_URL}/partners/getriderdetail/?userid=${id}`
        );
        console.log("riderdataresponse", riderdataresponse.data.details);
        setRiderdata(riderdataresponse.data.details);
      } catch (error) {
        console.log("fetchmanagerList", error);
      }
    };

    const handleClickAway = () => {
      setOpen2("");
    };

    const { ref: materialRef } = usePlacesWidget({
      apiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
      onPlaceSelected: (place) => {
        console.log(place);

        setAddress(place.formatted_address);
        let city1, zipcode1, state1, suburb1;
        for (let i = 0; i < place.address_components.length; i++) {
          for (let j = 0; j < place.address_components[i].types.length; j++) {
            switch (place.address_components[i].types[j]) {
              case "locality":
                city1 = place.address_components[i].long_name;
                break;
              case "administrative_area_level_1":
                state1 = place.address_components[i].long_name;
                break;
              case "postal_code":
                zipcode1 = place.address_components[i].long_name;
                break;
              case "sublocality":
                suburb1 = place.address_components[i].long_name;
                break;
            }
          }
        }
        setCity(city1 || "");
        setState(state1 || "");
        setZipcode(zipcode1 || "");
        setSuburb(suburb1 || "");
      },

      options: {
        types: ["address" || "geocode"],
      },
    });

    const removeclient = async () => {
      setLoading(true);
      try {
        await axios
          .delete(
            `${process.env.REACT_APP_URL}/customers/delete/?customerid=${currentcustomerid}`
          )

          .then((res) => {
            if (res.data.status) {
              enqueueSnackbar("Deleted Successfully", {
                variant: "success",
                anchorOrigin: { vertical: "top", horizontal: "right" },
                autoHideDuration: 2000,
              });
              setCurrentcustomerid("");
              fetchtable(localStorage.getItem("tenantid"));
            }
            setLoading(false);
          })
          .catch((err) => {
            console.log(err);
            setLoading(false);
          });
      } catch (err) {
        console.log(err);
        setLoading(false);
      }
    };

    const fetchstafflist = async (oid) => {
      setLoading1(true);
      try {
        // await axios.get(`${process.env.REACT_APP_URL2}/orders/getorderprocessbyid?orderheaderid=${oid}`)
        await axios
          .get(
            `${process.env.REACT_APP_URL2}/client/orders/getorderprocessbyid?orderheaderid=${oid}`
          )

          .then((res) => {
            console.log(res);
            if (res.data.message === "Successful") {
              let arr = [];
              res.data.details.map((val, i) => {
                arr = [...arr, { ...val, sno: i + 1 }];
              });
              // setRows([...arr])
              setStaffdetaillist([...arr]);
              // console.log(res.data.Details)
              // console.log(arr)
              // setLoading(false)
            }
            setLoading1(false);
          })
          .catch((err) => {
            console.log(err);
            setLoading1(false);
          });
      } catch (err) {
        console.log(err);
        setLoading1(false);
      }
    };

    const staffearningsverify = async (sid) => {
      setLoading(true);
      try {
        // await axios.get(`${process.env.REACT_APP_URL2}/orders/getorderprocessbystatus`)
        await axios
          .put(`${process.env.REACT_APP_URL2}/staffs/earnings/update`, {
            staffearningsid: sid,
            verified: 1,
          })
          // await axios.get(`${process.env.REACT_APP_URL2}/staffs/earnings/?fromdate=2023-09-07&todate=2023-09-09`)

          .then((res) => {
            console.log(res);
            if (res.data.status) {
              // let arr = []
              // res.data.Details.map((val, i) => {
              //     arr = [...arr, { ...val, sno: i + 1 }];
              // })
              // // setArr(arr)
              // setRows(arr)
              // console.log(res.data.Details)
              // console.log(arr)
              // setLoading(false)
              enqueueSnackbar("Updated Successfully", {
                variant: "success",
                anchorOrigin: { vertical: "top", horizontal: "right" },
                autoHideDuration: 2000,
              });
              // setTimeout(() => {

              if (localStorage.getItem("appuserid")) {
                fetchtable(localStorage.getItem("appuserid"));
              }

              // }, 2000)
            }
          })
          .catch((err) => {
            console.log(err);
            setLoading(false);
          });
      } catch (err) {
        console.log(err);
        setLoading(false);
      }
    };

    const updateclient = async (sid) => {
      console.log({
        customerid: 1364,
        configid: 1,
        firstname: firstname,
        applocationid: tenantinfo.applolcationid,
        profileimage: "",
        dialcode: "+91",
        contactno: mobilenumber,
        devicetype: "",
        deviceid: "",
        // "customertoken": "123",
        address: address,
        suburb: suburb,
        city: city,
        state: state,
        postcode: zipcode,
        landmark: landmark,
        doorno: doorno,
        latitude: latlong.lat.toString(),
        longitude: latlong.lng.toString(),
        tenantid: parseInt(localStorage.getItem("tenantid")),
        //email,regno,tenantname
      });
      setLoading(true);
      try {
        // await axios.get(`${process.env.REACT_APP_URL2}/orders/getorderprocessbystatus`)
        await axios
          .put(`${process.env.REACT_APP_URL}/staffs/earnings/update12`, {
            customerid: 1364,
            configid: 1,
            firstname: firstname,
            applocationid: tenantinfo.applolcationid,
            profileimage: "",
            dialcode: "+91",
            contactno: mobilenumber,
            devicetype: "",
            deviceid: "",
            // "customertoken": "123",
            address: address,
            suburb: suburb,
            city: city,
            state: state,
            postcode: zipcode,
            landmark: landmark,
            doorno: doorno,
            latitude: latlong.lat.toString(),
            longitude: latlong.lng.toString(),
            tenantid: parseInt(localStorage.getItem("tenantid")),
            //email,regno,tenantname
          })

          .then((res) => {
            console.log(res);
            if (res.data.status) {
              // let arr = []
              // res.data.Details.map((val, i) => {
              //     arr = [...arr, { ...val, sno: i + 1 }];
              // })
              // // setArr(arr)
              // setRows(arr)
              // console.log(res.data.Details)
              // console.log(arr)
              // setLoading(false)
              enqueueSnackbar("Updated Successfully", {
                variant: "success",
                anchorOrigin: { vertical: "top", horizontal: "right" },
                autoHideDuration: 2000,
              });
              // setTimeout(() => {

              // if (localStorage.getItem('appuserid')) {
              //     fetchtable(localStorage.getItem('appuserid'))

              // }

              // }, 2000)
            }
          })
          .catch((err) => {
            console.log(err);
            setLoading(false);
          });
      } catch (err) {
        console.log(err);
        setLoading(false);
      }
    };

    const updatestatus = async (uid, status1) => {
      setLoading(true);
      try {
        // await axios.get(`${process.env.REACT_APP_URL2}/orders/getorderprocessbystatus`)
        await axios
          .put(`${process.env.REACT_APP_URL}/partners/updaterider`, {
            userid: uid,
            status: status1 == "Active" ? "InActive" : "Active",
          })

          .then((res) => {
            console.log(res);
            if (res.data.status) {
              enqueueSnackbar("Updated Successfully", {
                variant: "success",
                anchorOrigin: { vertical: "top", horizontal: "right" },
                autoHideDuration: 2000,
              });
              fetchtable();
            }
          })
          .catch((err) => {
            console.log(err);
            setLoading(false);
          });
      } catch (err) {
        console.log(err);
        setLoading(false);
      }
    };

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

    const handleSelectAllClick = (event) => {
      if (event.target.checked) {
        const newSelected = rows.map((n) => n.name);
        setSelected(newSelected);
        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)
        );
      }

      setSelected(newSelected);
    };

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

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

    //   const handleChangeDense = (event) => {
    //     setDense(event.target.checked);
    //   };

    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 visibleRows = React.useMemo(
      () =>
        stableSort(rows, getComparator(order, orderBy)).slice(
          page * rowsPerPage,
          page * rowsPerPage + rowsPerPage
        ),
      [order, orderBy, page, rowsPerPage]
    );

    const handleClose = () => {
      setOpen(false);
    };

    function AlertCustomerDelete({ open, handleClose }) {
      // const [deletepassword, setDeletepassword] = useState('');

      return (
        <Dialog open={open} onClose={() => handleClose(false)} maxWidth="xs">
          <DialogContent sx={{ mt: 2, my: 1 }}>
            <Stack alignItems="center" spacing={3.5}>
              <Avatar
                color="error"
                sx={{ width: 72, height: 72, fontSize: "1.75rem" }}
              >
                <DeleteFilled />
              </Avatar>
              {/* <Grid >
                      <Chip label={orderid.slice(4)} variant="combined" color='warning' size='small' />
                    </Grid> */}
              <Stack spacing={2}>
                <Typography variant="h4" align="center">
                  Are you sure you want to Remove this Client?
                </Typography>
              </Stack>

              <Stack direction="row" spacing={2} sx={{ width: 1 }}>
                <Button
                  fullWidth
                  color="error"
                  variant="contained"
                  onClick={() => {
                    // if (deletepassword === orderid.slice(4)) {
                    //   cancelorder();
                    removeclient();
                    handleClose(true);
                    // }
                  }}
                  autoFocus
                >
                  Yes, Remove
                </Button>
                <Button
                  fullWidth
                  onClick={() => {
                    handleClose(false);
                    setCurrentcustomerid("");
                  }}
                  color="secondary"
                  variant="outlined"
                >
                  No
                </Button>
              </Stack>
            </Stack>
          </DialogContent>
        </Dialog>
      );
    }

    return (
      <>
        {loading && <Loader />}
        <AlertCustomerDelete open={open} handleClose={handleClose} />

        <Box
          sx={{
            width: "100%",
          }}
        >
          <TableContainer
            sx={{ width: "100%", borderBottom: 1, borderColor: "divider" }}
          >
            <Table
              sx={{ minWidth: 750 }}
              aria-labelledby="tableTitle"
              size={"medium"}
            >
              <EnhancedTableHead
                numSelected={selected.length}
                order={order}
                orderBy={orderBy}
                onSelectAllClick={handleSelectAllClick}
                onRequestSort={handleRequestSort}
                rowCount={rows.length}
              />

              {loading && (
                <>
                  <TableBody>
                    {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((item) => (
                      <TableRow key={item}>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </>
              )}

              <TableBody>
                {visibleRows.length == 0 && !loading && (
                  <>
                    <TableCell colSpan={10}>
                      <Stack
                        width={"100%"}
                        direction={"row"}
                        justifyContent={"center"}
                      >
                        <Empty />
                      </Stack>
                    </TableCell>
                    {/* <div>empty</div> */}
                  </>
                )}
                {visibleRows.map((row, index) => {
                  const isItemSelected = isSelected(row.sno);
                  const labelId = `enhanced-table-checkbox-${index}`;

                  return (
                    <>
                      <TableRow
                        hover
                        onClick={(event) => handleClick(event, row.sno)}
                        role="checkbox"
                        aria-checked={isItemSelected}
                        tabIndex={-1}
                        key={row.sno}
                        sx={{ cursor: "pointer" }}
                      >
                        <TableCell
                          component="th"
                          id={labelId}
                          scope="row"
                          padding="none"
                        >
                          {row.sno}
                        </TableCell>
                        <TableCell
                          align="left"
                          sx={{ paddingLeft: "0px !important" }}
                        >
                          <Stack
                            direction="row"
                            alignItems="center"
                            spacing={1}
                            justifyContent="flex-start"
                          >
                            <Avatar
                              alt="A"
                              size="sm"
                              src={row.tenantimage}
                              sx={{
                                width: "25px",
                                height: "25px",
                              }}
                            />

                            {/* <img src={row.tenantimage} width='25px' alt='a' /> */}
                            <Stack direction="column">
                              <Typography variant="caption">{`${row.firstname} ${row.lastname}`}</Typography>
                              <Typography
                                variant="caption"
                                color="textSecondary"
                              >
                                {/* {row.identification}*/}
                                {row.contactno}
                              </Typography>
                            </Stack>
                          </Stack>
                        </TableCell>
                        <TableCell align="left">
                          <Stack direction="column">
                            {/* <Typography variant="caption"  > {row.eventname}</Typography> */}
                            <Tooltip title={row.address}>
                              <Typography
                                variant="caption"
                                color="textSecondary"
                              >
                                {/* {row.pickupaddress.slice(0, 20)} */}
                                {row.suburb || row.address.slice(0, 20)}
                              </Typography>
                            </Tooltip>{" "}
                            <Typography>{row.city}</Typography>
                          </Stack>
                        </TableCell>
                        <TableCell align="left">{row.vehicleno}</TableCell>
                        <TableCell>{row.shiftid}</TableCell>
                        <TableCell sx={{ textAlign: "center" }}>
                          <Typography variant="caption">
                            {dayjs(
                              `${dayjs().format("MM-DD-YYYY")} ${row.starttime}`
                            )
                              // .utc()
                              .format("hh:mm A")}
                          </Typography>
                          <br />
                          {/* <Typography variant="caption">to</Typography> <br /> */}
                          <Typography variant="caption">
                            {dayjs(
                              `${dayjs().format("MM-DD-YYYY")} ${row.endtime}`
                            )
                              // .utc()
                              .format("hh:mm A")}
                          </Typography>
                        </TableCell>
                        {/* <TableCell align="left">
                                                    <Stack direction="column">
                                                        <Typography variant="caption">
                                                            {row.staffname}
                                                        </Typography>
                                                        <Grid>
                                                            <Chip label={row.productname} color="info" variant="light" size="small" />
                                                        </Grid>
                                                    </Stack>
                                                </TableCell> */}
                        <TableCell align="left">{row.basefare}</TableCell>
                        <TableCell align="left">{row.fuelcharge}</TableCell>
                        <TableCell>
                          {/* {row.status} */}
                          {row.status == "Active" && (
                            <Chip
                              label="Active"
                              color="success"
                              size="small"
                              sx={{ minWidth: 70 }}
                            />
                          )}
                          {row.status == "InActive" && (
                            <Chip
                              label="Inactive"
                              color="error"
                              size="small"
                              sx={{ minWidth: 70 }}
                            />
                          )}
                        </TableCell>

                        <TableCell>
                          <IconButton
                            aria-label="expand row"
                            size="small"
                            onClick={() => {
                              fetchRiderData(row.userid);
                              setOpenRow(
                                openRow === row.userid ? null : row.userid
                              );
                            }}
                            sx={{
                              bgcolor:
                                openRow === row.userid ? "primary.main" : null,
                              color: openRow === row.userid ? "white" : null,
                              "&:hover": {
                                bgcolor:
                                  openRow === row.userid
                                    ? "primary.main"
                                    : "#e1bee7",
                              },
                            }}
                          >
                            <Tooltip title="View Tenants" placement="top">
                              {openRow === row.userid ? (
                                <KeyboardArrowUpIcon />
                              ) : (
                                <KeyboardArrowDownIcon />
                              )}
                            </Tooltip>
                          </IconButton>
                          <IconButton
                            aria-describedby={`aria-${row.sno}`}
                            onClick={(e) => {
                              e.stopPropagation();
                              setAnchorEl(e.currentTarget);
                              setOpen2(row.sno);
                            }}
                          >
                            <MoreOutlined />
                          </IconButton>
                          <Popper
                            id={`aria-${row.sno}`}
                            // open={open2 == index + 1}
                            open={open2 == row.sno}
                            // open={true}
                            anchorEl={anchorEl}
                            placement="bottom-end"
                            sx={{
                              zIndex: 5000,
                              p: 0,
                            }}
                          >
                            <>
                              <Box
                                sx={{
                                  backgroundColor: "#fff",
                                  px: 2,
                                  py: 1,
                                  cursor: "pointer",
                                  boxShadow: theme.customShadows.z1,
                                }}
                                onClick={() => {
                                  //   setDialogopen(true)
                                  updatestatus(row.userid, row.status);
                                  handleClickAway();
                                }}
                              >
                                <ClickAwayListener
                                  onClickAway={handleClickAway}
                                >
                                  <Typography>
                                    {row.status == "Active"
                                      ? "Inactive"
                                      : "Active"}
                                  </Typography>
                                </ClickAwayListener>
                              </Box>
                              <Box
                                sx={{
                                  backgroundColor: "#fff",
                                  px: 2,
                                  py: 1,
                                  cursor: "pointer",
                                  boxShadow: theme.customShadows.z1,
                                }}
                                onClick={() => {
                                  navigate("/riders/edit", {
                                    state: { riderdata: row },
                                  });
                                }}
                              >
                                <Typography>Edit</Typography>
                              </Box>
                            </>
                          </Popper>
                        </TableCell>
                      </TableRow>

                      {/* //  ============================================ || collapsive row (rider data ) || ============================================ */}
                      <TableRow>
                        <TableCell
                          style={{
                            paddingBottom: 0,
                            paddingTop: 0,
                            paddingLeft: 0,
                            paddingRight: 0,
                          }}
                          colSpan={10}
                          sx={{ width: "100%" }}
                        >
                          <Collapse
                            in={openRow === row.userid}
                            timeout="auto"
                            unmountOnExit
                          >
                            <Grid container spacing={3} sx={{ p: 2 }}>
                              <Grid item xs={12} sm={5} md={4} xl={3}>
                                <Grid container spacing={3}>
                                  <Grid item xs={12}>
                                    <MainCard>
                                      <Grid container spacing={3}>
                                        <Grid item xs={12}>
                                          <Stack
                                            spacing={2.5}
                                            alignItems="center"
                                          >
                                            <Avatar
                                              alt="Avatar 1"
                                              size="xl"
                                              // src={avatarImage(`./default.png`)}
                                            />
                                            <Stack
                                              spacing={0.5}
                                              alignItems="center"
                                            >
                                              <Typography variant="h5">
                                                {row.fullname}
                                              </Typography>
                                              <Typography color="secondary">
                                                Nearle Rider
                                              </Typography>
                                            </Stack>
                                          </Stack>
                                        </Grid>
                                        <Grid item xs={12}>
                                          <Divider />
                                        </Grid>
                                        <Grid item xs={12}>
                                          <Stack
                                            direction="row"
                                            justifyContent="space-around"
                                            alignItems="center"
                                          >
                                            <Stack
                                              spacing={0.5}
                                              alignItems="center"
                                            >
                                              <Typography variant="h6">
                                                {riderdata.shifthours}
                                              </Typography>
                                              <Typography color="secondary">
                                                Shift
                                              </Typography>
                                            </Stack>
                                            <Divider
                                              orientation="vertical"
                                              flexItem
                                            />
                                            <Stack
                                              spacing={0.5}
                                              alignItems="center"
                                            >
                                              <Typography variant="h6">
                                                {`${riderdata?.starttime?.substring(
                                                  0,
                                                  2
                                                )} -  ${riderdata?.endtime?.substring(
                                                  0,
                                                  2
                                                )}`}
                                              </Typography>

                                              <Typography color="secondary">
                                                Timing
                                              </Typography>
                                            </Stack>
                                            <Divider
                                              orientation="vertical"
                                              flexItem
                                            />
                                            <Stack
                                              spacing={0.5}
                                              alignItems="center"
                                            >
                                              <Typography variant="h6">
                                                {riderdata.basefare}
                                              </Typography>
                                              <Typography color="secondary">
                                                Fare
                                              </Typography>
                                            </Stack>
                                          </Stack>
                                        </Grid>
                                        <Grid item xs={12}>
                                          <Divider />
                                        </Grid>
                                        <Grid item xs={12}>
                                          <List
                                            component="nav"
                                            aria-label="main mailbox folders"
                                            sx={{
                                              py: 0,
                                              "& .MuiListItem-root": {
                                                p: 0,
                                                py: 1,
                                              },
                                            }}
                                          >
                                            <ListItem>
                                              <ListItemIcon>
                                                <PhoneOutlined />
                                              </ListItemIcon>
                                              <ListItemSecondaryAction>
                                                <Typography align="right">
                                                  {riderdata.contactno}
                                                </Typography>
                                              </ListItemSecondaryAction>
                                            </ListItem>
                                            <ListItem>
                                              <ListItemIcon>
                                                <MailOutlined />
                                              </ListItemIcon>
                                              <ListItemSecondaryAction>
                                                <Typography align="right">
                                                  {riderdata.email}
                                                </Typography>
                                              </ListItemSecondaryAction>
                                            </ListItem>
                                          </List>
                                        </Grid>
                                      </Grid>
                                    </MainCard>
                                  </Grid>
                                </Grid>
                              </Grid>
                              <Grid item xs={12} sm={7} md={8} xl={9}>
                                <Box
                                  sx={{
                                    borderBottom: 1,
                                    borderColor: "divider",
                                  }}
                                >
                                  <Tabs
                                    value={value}
                                    onChange={handleChange}
                                    aria-label="basic tabs example"
                                  >
                                    <Tab
                                      label="Personal Details"
                                      {...a11yProps(0)}
                                    />
                                    <Tab
                                      label="Bank Details"
                                      {...a11yProps(1)}
                                    />
                                    <Tab
                                      label="Vehicle Details"
                                      {...a11yProps(2)}
                                    />
                                  </Tabs>
                                </Box>
                                <CustomTabPanel value={value} index={0}>
                                  <MainCard>
                                    <List sx={{ py: 0 }}>
                                      <ListItem divider={!matchDownMD}>
                                        <Grid container spacing={3}>
                                          <Grid item xs={12}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                Address
                                              </Typography>
                                              <Typography>
                                                {riderdata.address}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                        </Grid>
                                      </ListItem>
                                      <ListItem divider={!matchDownMD}>
                                        <Grid container spacing={3}>
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                Location
                                              </Typography>
                                              <Typography>
                                                {riderdata.suburb}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                City
                                              </Typography>
                                              <Typography>
                                                {riderdata.city}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                        </Grid>
                                      </ListItem>

                                      <ListItem divider>
                                        <Grid
                                          container
                                          spacing={matchDownMD ? 0.5 : 3}
                                        >
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                State
                                              </Typography>
                                              <Typography>
                                                {riderdata.state}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                        </Grid>
                                      </ListItem>
                                      <ListItem>
                                        <Grid
                                          container
                                          spacing={matchDownMD ? 0.5 : 3}
                                        >
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                Rider Id
                                              </Typography>
                                              <Typography>
                                                {riderdata.riderid}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                Identification No
                                              </Typography>
                                              <Typography>
                                                {riderdata.identificationno}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                        </Grid>
                                      </ListItem>
                                    </List>
                                  </MainCard>
                                </CustomTabPanel>
                                <CustomTabPanel value={value} index={1}>
                                  <MainCard>
                                    <List sx={{ py: 0 }}>
                                      <ListItem divider>
                                        <Grid
                                          container
                                          spacing={matchDownMD ? 0.5 : 3}
                                        >
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                A/C No
                                              </Typography>
                                              <Typography>
                                                {riderdata.accountno}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                A/C Holder
                                              </Typography>
                                              <Typography>
                                                {riderdata.accountname}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                        </Grid>
                                      </ListItem>
                                      <ListItem divider>
                                        <Grid
                                          container
                                          spacing={matchDownMD ? 0.5 : 3}
                                        >
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                A/C Type
                                              </Typography>
                                              <Typography>
                                                {riderdata.accounttype}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                Bank Name
                                              </Typography>
                                              <Typography>
                                                {riderdata.bankname}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                        </Grid>
                                      </ListItem>
                                      <ListItem>
                                        <Grid
                                          container
                                          spacing={matchDownMD ? 0.5 : 3}
                                        >
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                IFSC
                                              </Typography>
                                              <Typography>
                                                {riderdata.ifsccode}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                Branch
                                              </Typography>
                                              <Typography>
                                                {riderdata.branch}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                        </Grid>
                                      </ListItem>
                                    </List>
                                  </MainCard>
                                </CustomTabPanel>
                                <CustomTabPanel value={value} index={2}>
                                  <MainCard>
                                    <List sx={{ py: 0 }}>
                                      <ListItem divider>
                                        <Grid
                                          container
                                          spacing={matchDownMD ? 0.5 : 3}
                                        >
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                Vehicle Name
                                              </Typography>
                                              <Typography>
                                                {riderdata.vehiclename}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                Vehicle No
                                              </Typography>
                                              <Typography>
                                                {riderdata.vehicleno}{" "}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                        </Grid>
                                      </ListItem>

                                      <ListItem divider>
                                        <Grid
                                          container
                                          spacing={matchDownMD ? 0.5 : 3}
                                        >
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                Color
                                              </Typography>
                                              <Typography>
                                                {riderdata.color}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                Model
                                              </Typography>
                                              <Typography>
                                                {riderdata.model}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                        </Grid>
                                      </ListItem>
                                      <ListItem divider>
                                        <Grid
                                          container
                                          spacing={matchDownMD ? 0.5 : 3}
                                        >
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                Liscence No
                                              </Typography>
                                              <Typography>
                                                {riderdata.licenseno}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                Insurance No
                                              </Typography>
                                              <Typography>
                                                {riderdata.insuranceno}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                        </Grid>
                                      </ListItem>
                                      <ListItem>
                                        <Grid
                                          container
                                          spacing={matchDownMD ? 0.5 : 3}
                                        >
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary">
                                                Insurance Expiry Date
                                              </Typography>
                                              <Typography>
                                                {riderdata.insurancedate}
                                              </Typography>
                                            </Stack>
                                          </Grid>
                                          <Grid item xs={12} md={6}>
                                            <Stack spacing={0.5}>
                                              <Typography color="secondary"></Typography>
                                              <Typography></Typography>
                                            </Stack>
                                          </Grid>
                                        </Grid>
                                      </ListItem>
                                    </List>
                                  </MainCard>
                                </CustomTabPanel>
                              </Grid>
                            </Grid>
                          </Collapse>
                        </TableCell>
                      </TableRow>
                    </>
                  );
                })}
                {emptyRows > 0 && (
                  <TableRow
                    style={{
                      height: 53 * emptyRows,
                    }}
                  >
                    <TableCell colSpan={9} />
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </TableContainer>
          <TablePagination
            rowsPerPageOptions={[10, 25, 50, 100]}
            component="div"
            count={rows.length}
            rowsPerPage={rowsPerPage}
            page={page}
            onPageChange={handleChangePage}
            onRowsPerPageChange={handleChangeRowsPerPage}
          />
        </Box>
      </>
    );
  }

  return (
    <>
      <Grid container rowSpacing={2} columnSpacing={2.75}>
        <Grid item xs={12}>
          <Stack
            direction="row"
            justifyContent="space-between"
            alignItems="center"
          >
            <Typography variant="h3">Riders</Typography>
          </Stack>
        </Grid>

        <Grid item xs={12}>
          <Box
            sx={{
              overflow: "auto",
              border: 1,
              borderColor: "grey.200",
              borderRadius: 2,
              backgroundColor: "#fff",
              minHeight: 400,
            }}
          >
            <Stack
              alignItems="center"
              justifyContent="flex-end"
              direction="row"
              sx={{
                p: 2,
                width: "100%",
              }}
            >
              <FormControl
                sx={{
                  width: 250,
                }}
              >
                <OutlinedInput
                  inputRef={textFieldRef}
                  size="small"
                  id="header-search5"
                  aria-describedby="header-search-text"
                  inputProps={{
                    "aria-label": "weight",
                  }}
                  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("");
                        fetchtable();
                      }}
                    >
                      <ClearIcon
                        style={{ fontSize: "medium", color: "#65387A" }}
                      />
                    </IconButton>
                  }
                />
              </FormControl>
            </Stack>

            <EnhancedTable />
          </Box>
        </Grid>
      </Grid>
    </>
  );
};

export default Riders;
