import React, { useState, useEffect, useCallback } from "react";
import {
  cacheData,
  clearCacheKey,
  getCachedData,
  getCachedProfileData,
} from "../../slices/apiDataManager";
import Breadcrumb from "../../components/common/Breadcrumb";
import AttendanceLog from "../../components/Activities/AttendcesLogs";
import Attendance from "../../components/Activities/Attendance";
import Regularization from "../../components/Activities/Regularization";
import { useAttendance } from "../../hooks/useAttendance";
import { useDispatch, useSelector } from "react-redux";
import { setProjectId } from "../../slices/localVariablesSlice";
import { hasUserPermission } from "../../utils/authUtils";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { REGULARIZE_ATTENDANCE } from "../../utils/constants";
import eventBus from "../../services/eventBus";
import { useProjectName } from "../../hooks/useProjects";
import GlobalModel from "../../components/common/GlobalModel";
import CheckCheckOutmodel from "../../components/Activities/CheckCheckOutForm";
import AttendLogs from "../../components/Activities/AttendLogs";
import { useQueryClient } from "@tanstack/react-query";

const AttendancePage = () => {
  const [activeTab, setActiveTab] = useState("all");
  const [ShowPending, setShowPending] = useState(false);
  const queryClient = useQueryClient();
  const loginUser = getCachedProfileData();
  const selectedProject = useSelector((store) => store.localVariables.projectId);
  const dispatch = useDispatch();

  const [attendances, setAttendances] = useState();
  const [empRoles, setEmpRoles] = useState(null);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [modelConfig, setModelConfig] = useState();
  const DoRegularized = useHasUserPermission(REGULARIZE_ATTENDANCE);
  const { projectNames, loading: projectLoading, fetchData } = useProjectName();

  const [formData, setFormData] = useState({
    markTime: "",
    description: "",
    date: new Date().toLocaleDateString(),
  });

  useEffect(() => {
    if (selectedProject == null) {
      dispatch(setProjectId(projectNames[0]?.id));
    }
  }, []);

  const getRole = (roleId) => {
    if (!empRoles) return "Unassigned";
    if (!roleId) return "Unassigned";
    const role = empRoles.find((b) => b.id == roleId);
    return role ? role.role : "Unassigned";
  };

  const openModel = () => {
    setIsCreateModalOpen(true);
  };

  const handleModalData = (employee) => {
    setModelConfig(employee);
  };

  const closeModal = () => {
    setModelConfig(null);
    setIsCreateModalOpen(false);
  };

  const handleToggle = (event) => {
    setShowOnlyCheckout(event.target.checked);
  };


  useEffect(() => {
    if (modelConfig !== null) {
      openModel();
    }
  }, [modelConfig, isCreateModalOpen]);

  return (
    <>
      {isCreateModalOpen && modelConfig && (
        <GlobalModel
          isOpen={isCreateModalOpen}
          size={modelConfig?.action === 6 && "lg"}
          closeModal={closeModal}
        >
          {(modelConfig?.action === 0 ||
            modelConfig?.action === 1 ||
            modelConfig?.action === 2) && (
            <CheckCheckOutmodel
              modeldata={modelConfig}
              closeModal={closeModal}
            />
          )}
          {/* For view logs */}
          {modelConfig?.action === 6 && (
            <AttendLogs Id={modelConfig?.id} closeModal={closeModal} />
          )}
          {modelConfig?.action === 7 && (
            <Confirmation closeModal={closeModal} />
          )}
        </GlobalModel>
      )}

      <div className="container-fluid">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Attendance", link: null },
          ]}
        ></Breadcrumb>
        <div className="nav-align-top nav-tabs-shadow" >
          <ul className="nav nav-tabs" role="tablist">
            <li className="nav-item">
              <button
                type="button"
                className={`nav-link ${
                  activeTab === "all" ? "active" : ""
                } fs-6`}
                onClick={() => setActiveTab("all")}
                data-bs-toggle="tab"
                data-bs-target="#navs-top-home"
              >
                Today's
              </button>
            </li>
            <li className="nav-item">
              <button
                type="button"
                className={`nav-link ${
                  activeTab === "logs" ? "active" : ""
                } fs-6`}
                onClick={() => setActiveTab("logs")}
                data-bs-toggle="tab"
                data-bs-target="#navs-top-profile"
              >
                Logs
              </button>
            </li>
            <li className={`nav-item ${!DoRegularized && "d-none"}`}>
              <button
                type="button"
                className={`nav-link ${
                  activeTab === "regularization" ? "active" : ""
                } fs-6`}
                onClick={() => setActiveTab("regularization")}
                data-bs-toggle="tab"
                data-bs-target="#navs-top-messages"
              >
                Regularization
              </button>
            </li>
          </ul>
          <div className="tab-content attedanceTabs py-0 px-1 px-sm-3">
  {selectedProject ? (
    <>
      {activeTab === "all" && (
        <div className="tab-pane fade show active py-0">
          <Attendance handleModalData={handleModalData} getRole={getRole} />
        </div>
      )}
      {activeTab === "logs" && (
        <div className="tab-pane fade show active py-0">
          <AttendanceLog handleModalData={handleModalData} />
        </div>
      )}
      {activeTab === "regularization" && DoRegularized && (
        <div className="tab-pane fade show active py-0">
          <Regularization />
        </div>
      )}
    </>
  ) : (
   <div className="py-2">
     <small className="py-2">Please Select Project!</small>
   </div>
  )}
</div>

        </div>
      </div>
    </>
  );
};

export default AttendancePage;
