import PropTypes from "prop-types";
import * as React from "react";
import { useState, useRef, useEffect } from "react";
import TitleCard from "pages/titleCard";
import axios from "axios";
import { DemoContainer } from "@mui/x-date-pickers/internals/demo";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { useQuery } from "@tanstack/react-query";
import { Empty } from "antd";

import { fetchLocations } from "pages/api/api";

// material-ui
import {
  Box,
  Checkbox,
  Divider,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableSortLabel,
  TableRow,
  FormControl,
  OutlinedInput,
  InputAdornment,
  Chip,
  Tooltip,
  IconButton,
  Stack,
  Dialog,
  DialogTitle,
  DialogContent,
  Typography,
  Button,
  Autocomplete,
  TextField,
} from "@mui/material";
import Loader from "components/Loader";

import { DateRangePicker } from "mui-daterange-picker";
import {
  addDays,
  addMonths,
  addWeeks,
  // addYears,
  endOfMonth,
  endOfWeek,
  // endOfYear,
  startOfMonth,
  startOfWeek,
  // startOfYear,
} from "date-fns";
import { FilterList } from "@mui/icons-material";

import dayjs from "dayjs";
var utc = require("dayjs/plugin/utc");
dayjs.extend(utc);
import { visuallyHidden } from "@mui/utils";
import { SearchOutlined, CloseOutlined } from "@ant-design/icons";

// project imports
import MainCard from "components/MainCard";
import {
  CSVExport,
  TableRowSelection,
} from "components/third-party/ReactTable";

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

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

function stableSort(array, comparator) {
  const stabilizedThis = array.map((el, index) => [el, index]);
  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0]);
    if (order !== 0) return order;
    return a[1] - b[1];
  });
  return stabilizedThis.map((el) => el[0]);
}
function formatDate(dateString) {
  const date = dayjs(dateString);
  const formattedDate = date.format("DD-MM-YYYY ");
  return formattedDate;
}

const formatTime = (timeString) =>
  new Date("2024-01-01T" + timeString + "Z").toLocaleTimeString("en-US", {
    timeZone: "UTC",
    hour12: true,
    hour: "2-digit",
    minute: "2-digit",
  });

// table header
const headCells = [
  {
    id: "s.no",
    numeric: false,
    disablePadding: false,
    label: "S.No",
  },
  {
    id: "userid",
    numeric: false,
    disablePadding: false,
    label: "Id",
  },
  {
    id: "riderName",
    numeric: false,
    disablePadding: false,
    label: "Rider",
  },
  {
    id: "logdate",
    numeric: false,
    disablePadding: false,
    label: "logdate",
  },
  {
    id: "shifthours",
    numeric: false,
    disablePadding: false,
    label: "Shift(hrs)",
  },
  {
    id: "login",
    numeric: false,
    disablePadding: false,
    label: "login",
  },
  {
    id: "logout",
    numeric: false,
    disablePadding: false,
    label: "logout",
  },
  {
    id: "workhours",
    numeric: false,
    disablePadding: false,
    label: "wrk(hrs)",
  },
  {
    id: "shorthours",
    numeric: false,
    disablePadding: false,
    label: "sht(hrs)",
  },
  {
    id: "breakhours",
    numeric: false,
    disablePadding: false,
    label: `brk(hrs)`,
  },
  {
    id: "logstatus",
    numeric: false,
    disablePadding: false,
    label: "status",
  },
];

// ==============================|| 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 ? "right" : "left"}
            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>
  );
}

// ==============================|| RidersLogs ||============================== //

export default function RidersLogs() {
  const [rows, setRows] = React.useState([]);
  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] = React.useState(false);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [selectedValue, setSelectedValue] = React.useState([]);
  const [dateselect, setDateselect] = useState("select");
  const [startdate, setStartdate] = useState(dayjs().format("YYYY-MM-DD"));
  const [enddate, setEnddate] = useState(dayjs().format("YYYY-MM-DD"));
  const [open, setOpen] = useState(false);
  const [partid, setPartId] = useState(-1);
  // const partid = window.localStorage.getItem("partnerid");
  const [searchword, setSearchword] = useState("");
  const [showClose, SetShowClose] = useState(false);
  const [id, setid] = useState(-1);
  const textFieldRef = useRef(null);

  const [appId, setAppId] = useState(0);
  const [locaName, setLocoName] = useState("All");
  const [locations, setLocations] = useState("All");

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

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

  const fetchRidersLogs = async () => {
    try {
      let logsResponse = await axios.get(
        appId == 0
          ? `https://jupiter.nearle.app/live/api/v1/partners/getriderlogs/?fromdate=${startdate}`
          : `https://jupiter.nearle.app/live/api/v1/partners/getriderlogs/?applocationid=${appId}&fromdate=${startdate}`
      );
      console.log("logsResponse", logsResponse.data.details);
      setRows(logsResponse.data.details);
    } catch (error) {
      console.log("fetchRidersLogs", error);
    }
  };
  React.useEffect(() => {
    fetchRidersLogs();
  }, [startdate, enddate, appId]);

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

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

  const handleClick = (event, name) => {
    const selectedIndex = selected.indexOf(name);
    let newSelected = [];

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

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

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

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

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

  React.useEffect(() => {
    if (searchword !== "") {
      let filteredRows = rows.filter((row) => {
        return (
          row.username.toLowerCase().includes(searchword.toLowerCase()) ||
          row.userid.toString().includes(searchword)
        );
      });
      setRows([...filteredRows]);
    } else {
      fetchRidersLogs();
    }
  }, [searchword]);

  return (
    <>
      <TitleCard title="Riders Logs" />{" "}
      <MainCard
        content={false}
        sx={{ mt: "10px" }}
        title={
          <FormControl sx={{ width: 250, display: { xs: "none", md: "flex" } }}>
            <OutlinedInput
              inputRef={textFieldRef}
              sx={{ background: "white" }}
              size="medium"
              id="header-search"
              startAdornment={
                <InputAdornment position="start" sx={{ mr: -0.5 }}>
                  <SearchOutlined />
                </InputAdornment>
              }
              endAdornment={
                showClose && (
                  <InputAdornment position="end" sx={{ mr: -0.5 }}>
                    <CloseOutlined
                      onClick={() => {
                        setSearchword("");
                        SetShowClose(false);
                      }}
                    />
                  </InputAdornment>
                )
              }
              aria-describedby="header-search-text"
              inputProps={{
                "aria-label": "weight",
              }}
              placeholder="Search (ctrl+k)"
              value={searchword}
              onChange={(e) => {
                setSearchword(e.target.value);
                if (e.target.value == "") {
                  SetShowClose(false);
                } else {
                  SetShowClose(true);
                }
              }}
              autoComplete="off"
            />
          </FormControl>
        }
        secondary={
          <>
            <Stack direction={"row"} spacing={1} alignItems={"center"}>
              <Autocomplete
                disablePortal
                id="combo-box-demo"
                options={locations}
                getOptionLabel={(option) => `${option.locationname}`}
                sx={{ width: 300, height: 33 }}
                onChange={(event, value, reason) => {
                  if (reason === "clear") {
                    setAppId(0);
                    setLocoName("All");
                  } else {
                    console.log(value);
                    setAppId(value.applocationid);
                    setLocoName(value.locationname);
                  }
                }}
                renderInput={(params) => (
                  <TextField {...params} label={locaName} />
                )}
              />
              <LocalizationProvider dateAdapter={AdapterDayjs}>
                <DemoContainer components={["DatePicker"]}>
                  <DatePicker
                    label="Choose Date"
                    value={dayjs(startdate)}
                    format="DD-MM-YYYY"
                    onChange={(e) => {
                      console.log("date", dayjs(e.$d).format("YYYY-MM-DD"));
                      setStartdate(dayjs(e.$d).format("YYYY-MM-DD"));
                      setOpen(false);
                    }}
                  />
                </DemoContainer>
              </LocalizationProvider>
            </Stack>
          </>
        }
      >
        <TableRowSelection selected={selected.length} />

        {/* table */}
        <TableContainer>
          <Table
            sx={{ minWidth: 750 }}
            aria-labelledby="tableTitle"
            size={dense ? "small" : "medium"}
          >
            <EnhancedTableHead
              numSelected={selected.length}
              order={order}
              orderBy={orderBy}
              onSelectAllClick={handleSelectAllClick}
              onRequestSort={handleRequestSort}
              rowCount={rows.length}
            />
            <TableBody>
              {rows.length == 0 ? (
                <TableRow>
                  <TableCell colSpan={11}>
                    <Stack
                      width={"100%"}
                      direction={"row"}
                      justifyContent={"center"}
                    >
                      <Empty />
                    </Stack>
                  </TableCell>
                </TableRow>
              ) : (
                stableSort(rows, getComparator(order, orderBy))
                  .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                  .map((row, index) => {
                    if (typeof row === "number") return null;
                    const isItemSelected = isSelected(row.name);
                    const labelId = `enhanced-table-checkbox-${index}`;

                    return (
                      <TableRow
                        hover
                        //   onClick={(event) => handleClick(event, row.name)}
                        role="checkbox"
                        aria-checked={isItemSelected}
                        tabIndex={-1}
                        key={index}
                        selected={isItemSelected}
                      >
                        {/* <TableCell sx={{ pl: 3 }} padding="checkbox">
                        <Checkbox
                          color="primary"
                          checked={isItemSelected}
                          inputProps={{
                            'aria-labelledby': labelId
                          }}
                        />
                      </TableCell> */}
                        <TableCell align="left">{index + 1}</TableCell>
                        <TableCell align="left">{row.userid}</TableCell>
                        <TableCell align="left">{row.username}</TableCell>
                        <TableCell align="left">
                          {" "}
                          <Chip
                            label={formatDate(row.logdate)}
                            color="warning"
                            variant="outlined"
                            size="small"
                            sx={{ bgcolor: "#fffde7" }}
                          />
                        </TableCell>

                        <TableCell align="left">{row.shifthours}</TableCell>
                        <TableCell align="left">
                          {row.login != "" && (
                            <Chip
                              label={formatTime(row.login)}
                              color="info"
                              variant="outlined"
                              size="small"
                              sx={{ bgcolor: "#e0f7fa" }}
                            />
                          )}
                        </TableCell>
                        <TableCell align="left">
                          {row.logout != "" && (
                            <Chip
                              label={formatTime(row.logout)}
                              color="info"
                              variant="outlined"
                              size="small"
                              sx={{ bgcolor: "#e0f7fa" }}
                            />
                          )}
                        </TableCell>

                        <TableCell align="left">{row.workhours}</TableCell>
                        <TableCell align="left">{row.shorthours}</TableCell>
                        <TableCell align="left">{row.breakhours}</TableCell>
                        <TableCell align="left">
                          {row.logstatus == 0 ? (
                            <Chip
                              label="Active"
                              color="success"
                              variant="outlined"
                              size="small"
                              sx={{ bgcolor: "#e8f5e9" }}
                            />
                          ) : (
                            <Chip
                              label="Inactive"
                              color="error"
                              variant="outlined"
                              size="small"
                              sx={{ bgcolor: "#fce4ec" }}
                            />
                          )}
                        </TableCell>
                      </TableRow>
                    );
                  })
              )}

              {emptyRows > 0 && (
                <TableRow sx={{ height: (dense ? 33 : 53) * emptyRows }}>
                  <TableCell colSpan={6} />
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
        <Divider />
        {/* table pagination */}
        <TablePagination
          rowsPerPageOptions={[5, 10, 25]}
          component="div"
          count={rows.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        />
        <Dialog open={open}>
          <DialogTitle align="left">
            <Typography variant="h4">Select Date</Typography>
          </DialogTitle>
          <DialogContent sx={{ width: "100%" }} className="datedialog">
            <LocalizationProvider dateAdapter={AdapterDayjs}>
              <DemoContainer components={["DatePicker"]}>
                <DatePicker
                  label={dayjs(startdate).format("DD-MM-YYYY")}
                  onChange={(e) => {
                    console.log("date", dayjs(e.$d).format("YYYY-MM-DD"));
                    setStartdate(dayjs(e.$d).format("YYYY-MM-DD"));
                    setOpen(false);
                  }}
                />
              </DemoContainer>
            </LocalizationProvider>
          </DialogContent>
          <Stack
            direction="row"
            justifyContent="flex-end"
            sx={{ width: "100%", p: 2 }}
          >
            <Button
              variant="contained"
              size="small"
              onClick={() => setOpen(false)}
            >
              ok
            </Button>
          </Stack>
        </Dialog>
      </MainCard>
    </>
  );
}
