import React, { useEffect, useState } from "react";
import moment from "moment";
import Avatar from "../common/Avatar";
import { convertShortTime } from "../../utils/dateUtils";
import RenderAttendanceStatus from "./RenderAttendanceStatus";
import { useSelector, useDispatch } from "react-redux";
import { fetchAttendanceData } from "../../slices/apiSlice/attedanceLogsSlice";
import DateRangePicker from "../common/DateRangePicker";
import { getCachedData } from "../../slices/apiDataManager";
import usePagination from "../../hooks/usePagination";

const AttendanceLog = ({ handleModalData, projectId }) => {
  const [attendances, setAttendnaces] = useState([]);
  const [selectedDate, setSelectedDate] = useState("");
  const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
  const dispatch = useDispatch();
  const { data, loading, error } = useSelector((store) => store.attendanceLogs);
  const [isRefreshing, setIsRefreshing] = useState(true);

  const today = new Date();
  today.setHours(0, 0, 0, 0); // Strip time to compare dates only
  
  const isSameDay = (dateStr) => {
    if (!dateStr) return false;
    const d = new Date(dateStr);
    d.setHours(0, 0, 0, 0);
    return d.getTime() === today.getTime();
  };
  
  const isBeforeToday = (dateStr) => {
    if (!dateStr) return false;
    const d = new Date(dateStr);
    d.setHours(0, 0, 0, 0);
    return d.getTime() < today.getTime();
  };
  
  const sortByName = (a, b) => {
    const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
    const nameB = b.firstName.toLowerCase() + b.lastName.toLowerCase();
    return nameA.localeCompare(nameB);
  };
  
  const group1 = data.filter(d => d.activity === 1 && isSameDay(d.checkInTime)).sort(sortByName);
  const group2 = data.filter(d => d.activity === 4 && isSameDay(d.checkOutTime)).sort(sortByName);
  const group3 = data.filter(d => d.activity === 1 && isBeforeToday(d.checkInTime)).sort(sortByName);
  const group4 = data.filter(d => d.activity === 4 && isBeforeToday(d.checkOutTime)).sort(sortByName);
  const group5 = data.filter(d => d.activity === 5).sort(sortByName);
  
  const sortedFinalList = [...group1, ...group2, ...group3, ...group4, ...group5];

  const currentDate = new Date().toLocaleDateString( "en-CA" );
  const { currentPage, totalPages, currentItems, paginate } = usePagination(
    sortedFinalList,
    5
  );

  useEffect(() => {
    const { startDate, endDate } = dateRange;
    if (startDate && endDate) {
      dispatch(
        fetchAttendanceData({
          projectId,
          fromDate: startDate,
          toDate: endDate,
        })
      );
    }
  }, [dateRange, projectId, isRefreshing]);
  
  return (
    <>
      <div
        className="dataTables_length text-start py-2 d-flex justify-content-between"
        id="DataTables_Table_0_length"
      >
        <div className="col-md-3 my-0 ">
          <DateRangePicker onRangeChange={setDateRange} />
        </div>
        <div className="col-md-2 m-0 text-end">
          <i
            className={`bx bx-refresh cursor-pointer fs-4 ${
              loading ? "spin":"" 
            }`}
            title="Refresh"
            onClick={()=>setIsRefreshing(!isRefreshing)}
          />
        </div>
      </div>
      <div className="table-responsive text-nowrap">
        {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>
              {loading && <td colSpan={5}>Loading...</td>}
              {error && <td colSpan={5}>{error}</td>}
              {data && data.length === 0 && (
                <tr>
                  <td colSpan={5}>No Data Found</td>
                </tr>
              )}

              {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">
                    <RenderAttendanceStatus
                      attendanceData={attendance}
                      handleModalData={handleModalData}
                      Tab={2}
                      currentDate={currentDate}
                    />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <span>No employee logs</span>
        )}
      </div>
      {!loading && (
              <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>
            )}
    </>
  );
};

export default AttendanceLog;
