import React, { useState, useEffect } from "react";
import moment from "moment";
import DateRangePicker, { DateRangePicker1 } from "../common/DateRangePicker";
import { useDispatch, useSelector } from "react-redux";
import usePagination from "../../hooks/usePagination";
import Avatar from "../common/Avatar";
import { convertShortTime } from "../../utils/dateUtils";
import RenderAttendanceStatus from "../Activities/RenderAttendanceStatus";
import AttendLogs from "../Activities/AttendLogs";
import { useAttendanceByEmployee } from "../../hooks/useAttendance";
import GlobalModel from "../common/GlobalModel";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import { FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { localToUtc } from "../../utils/appUtils";
import { useParams } from "react-router-dom";
import { SpinnerLoader } from "../common/Loader";

const EmpAttendance = () => {
  const { employeeId } = useParams();
  const [attendances, setAttendnaces] = useState([]);
  const [selectedDate, setSelectedDate] = useState("");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [attendanceId, setAttendanecId] = useState();

  const methods = useForm({
    defaultValues: {
      startDate: moment().subtract(6, "days").format("DD-MM-YYYY"),
      endDate: moment().format("DD-MM-YYYY"),
    },
  });
  const { watch } = methods;

  const [startDate, endDate] = watch(["startDate", "endDate"]);
  const {
    data = [],
    isLoading: loading,
    isFetching,
    isError,
    error,
    refetch,
  } = useAttendanceByEmployee(
    employeeId,
    startDate ? localToUtc(startDate) : null,
    endDate ? localToUtc(endDate) : null
  );

  const dispatch = useDispatch();
  const sorted = [...data].sort(
    (a, b) =>
      new Date(b?.checkInTime).getTime() - new Date(a?.checkInTime).getTime()
  );


  const { currentPage, totalPages, currentItems, paginate } = usePagination(
    sorted,
    ITEMS_PER_PAGE
  );

  const openModal = (id) => {
    setAttendanecId(id);
    setIsModalOpen(true);
  };
  const closeModal = () => setIsModalOpen(false);

  return (
    <>
      {isModalOpen && (
        <GlobalModel size="lg" isOpen={isModalOpen} closeModal={closeModal}>
          <AttendLogs Id={attendanceId} />
        </GlobalModel>
      )}
      <div className="card px-4 mt-5 py-2 " style={{ minHeight: "500px" }}>
        <div
          className="dataTables_length text-start py-2 d-flex justify-content-between "
          id="DataTables_Table_0_length"
        >
          <div className="col-4 col-md-3 my-0 ">
            <>
              <FormProvider {...methods}>
                <DateRangePicker1 />
              </FormProvider>
            </>
          </div>
        </div>
        <div className="table-responsive text-nowrap">
          {!loading && data.length === 0 && (
            <div className="text-center py-5">No employee logs</div>
          )}

          {isError && <div className="text-center">{error.message}</div>}
          {loading && (
            <div className="d-flex justify-content-center align-items-center" style={{ minHeight: "200px" }}>
              <SpinnerLoader />
            </div>
          )}

          {data && data.length > 0 && (
            <table className="table mb-0">
              <thead>
                <tr>
                  <th className="border-top-1" colSpan={2}>
                    Name
                  </th>
                  <th className="border-top-1">Date</th>
                  <th>
                    <i className="bx bxs-down-arrow-alt text-success"></i>{" "}
                    Check-In
                  </th>
                  <th>
                    <i className="bx bxs-up-arrow-alt text-danger"></i>{" "}
                    Check-Out
                  </th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                {currentItems?.map((attendance, index) => (
                  <tr key={index}>
                    <td colSpan={2}>
                      <div className="d-flex justify-content-start align-items-center">
                        <Avatar
                          firstName={attendance.firstName}
                          lastName={attendance.lastName}
                        />
                        <div className="d-flex flex-column">
                          <a href="#" className="text-heading text-truncate">
                            <span className="fw-normal">
                              {attendance.firstName} {attendance.lastName}
                            </span>
                          </a>
                        </div>
                      </div>
                    </td>
                    <td>
                      {" "}
                      {moment(attendance.checkInTime).format("DD-MMM-YYYY")}
                    </td>
                    <td>{convertShortTime(attendance.checkInTime)}</td>
                    <td>
                      {attendance.checkOutTime
                        ? convertShortTime(attendance.checkOutTime)
                        : "--"}
                    </td>

                    <td className="text-center">
                      <button
                        type="button"
                        className="btn btn-xs btn-secondary ms-2"
                        tabIndex="0"
                        aria-controls="DataTables_Table_0"
                        data-bs-toggle="modal"
                        onClick={() => openModal(attendance.id)}
                      >
                        View
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
        {!loading && data.length > 20 && (
          <nav aria-label="Page ">
            <ul className="pagination pagination-sm justify-content-end py-1">
              <li
                className={`page-item  ${currentPage === 1 ? "disabled" : ""}`}
              >
                <button
                  className="page-link btn-xs"
                  onClick={() => paginate(currentPage - 1)}
                >
                  &laquo;
                </button>
              </li>
              {[...Array(totalPages)].map((_, index) => (
                <li
                  key={index}
                  className={`page-item ${currentPage === index + 1 ? "active" : ""
                    }`}
                >
                  <button
                    className="page-link "
                    onClick={() => paginate(index + 1)}
                  >
                    {index + 1}
                  </button>
                </li>
              ))}
              <li
                className={`page-item ${currentPage === totalPages ? "disabled" : ""
                  }`}
              >
                <button
                  className="page-link "
                  onClick={() => paginate(currentPage + 1)}
                >
                  &raquo;
                </button>
              </li>
            </ul>
          </nav>
        )}
      </div>
    </>
  );
};

export default EmpAttendance;
