import React, { useState, useEffect } from "react";
import moment from "moment";
import DateRangePicker from "../common/DateRangePicker";
import { useDispatch, useSelector } from "react-redux";
import { fetchEmployeeAttendanceData } from "../../slices/apiSlice/employeeAttendanceSlice";
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";

const EmpAttendance = ({ employee }) => {
  const [attendances, setAttendnaces] = useState([]);
  const [selectedDate, setSelectedDate] = useState("");
  const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [attendanceId, setAttendanecId] = useState();
  const {
    data = [],
    isLoading: loading,
    isFetching,
    error,
    refetch,
  } = useAttendanceByEmployee(employee, dateRange.startDate, dateRange.endDate);
  const dispatch = useDispatch();

  // const { data, loading, error } = useSelector(
  //   (store) => store.employeeAttendance
  // );

  const [isRefreshing, setIsRefreshing] = useState(true);

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  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 uniqueMap = new Map();

  [...group1, ...group2, ...group3, ...group4, ...group5].forEach((rec) => {
    const date = moment(rec.checkInTime || rec.checkOutTime).format(
      "YYYY-MM-DD"
    );
    const key = `${rec.employeeId}-${date}`;
    const existing = uniqueMap.get(key);
    if (
      !existing ||
      new Date(rec.checkInTime || rec.checkOutTime) >
        new Date(existing.checkInTime || existing.checkOutTime)
    ) {
      uniqueMap.set(key, rec);
    }
  });

  const sortedFinalList = [...uniqueMap.values()].sort(
    (a, b) =>
      new Date(b.checkInTime || b.checkOutTime) -
      new Date(a.checkInTime || a.checkOutTime)
  );

  const currentDate = new Date().toLocaleDateString("en-CA");
  const { currentPage, totalPages, currentItems, paginate } = usePagination(
    sortedFinalList,
    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-md-3 my-0 ">
            <DateRangePicker
              DateDifference="30"
              onRangeChange={setDateRange}
              endDateMode="today"
            />
          </div>
          <div className="col-md-2 m-0 text-end">
            <i
              className={`bx bx-refresh cursor-pointer fs-4 ${
                isFetching ? "spin" : ""
              }`}
              data-toggle="tooltip"
              title="Refresh"
              onClick={() => refetch()}
            />
          </div>
        </div>
        <div className="table-responsive text-nowrap">
          {!loading && data.length === 0 && <span>No employee logs</span>}
          {error && <div className="text-center">{error}</div>}
          {loading && !data && <div className="text-center">Loading...</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 && sortedFinalList.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;
