import React, { useState, useEffect } from "react";
import { cacheData, getCachedData, getCachedProfileData } from "../../slices/apiDataManager";
import Breadcrumb from "../../components/common/Breadcrumb";
import AttendanceLog from "../../components/Activities/AttendcesLogs";
import Attendance from "../../components/Activities/Attendance";
import AttendanceModel from "../../components/Activities/AttendanceModel";
import showToast from "../../services/toastService";
import { useProjects } from "../../hooks/useProjects";
import Regularization from "../../components/Activities/Regularization";
import { useAttendace } from "../../hooks/useAttendance";
import { useDispatch, useSelector } from "react-redux";
import { setProjectId } from "../../slices/localVariablesSlice";
import {markCurrentAttendance} from "../../slices/apiSlice/attendanceAllSlice";
import { hasUserPermission } from "../../utils/authUtils";
import {useHasUserPermission} from "../../hooks/useHasUserPermission";
import {REGULARIZE_ATTENDANCE} from "../../utils/constants";

const AttendancePage = () =>
{
  const loginUser = getCachedProfileData()
  var selectedProject = useSelector( ( store ) => store.localVariables.projectId )
  const {projects,loading:projectLoading} = useProjects()
  const {attendance,loading:attLoading} = useAttendace(selectedProject)
   const[attendances,setAttendances] = useState()
  const [empRoles, setEmpRoles] = useState(null);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [ modelConfig, setModelConfig ] = useState();
  const DoRegularized = useHasUserPermission(REGULARIZE_ATTENDANCE)
  const dispatch = useDispatch()
  
  const [formData, setFormData] = useState({
       time: "",
       description: "",
       date: new Date().toLocaleDateString(),
     });

  
  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 modalElement = document.getElementById("check-Out-modal");
    if (modalElement) {
      modalElement.classList.remove('show'); 
      modalElement.style.display = 'none'; 
      document.body.classList.remove('modal-open'); 
      document.querySelector('.modal-backdrop').remove(); 
    }  
  };
  
 
  const handleSubmit = ( formData ) =>{   
    dispatch( markCurrentAttendance( formData ) ).then( ( action ) =>
    {
      const updatedAttendance = attendances.map(item => 
        item.employeeId === action.payload.employeeId 
          ? { ...item, ...action.payload }  
          : item  
      );
      cacheData("Attendance", { data: updatedAttendance, projectId: selectedProject })
      setAttendances(updatedAttendance)
      showToast("Attedance Marked Successfully","success")     
    })
      .catch( ( error ) =>
      {
        showToast(error.message,"error")
    });
  };


  useEffect(() => {
    if (modelConfig !== null) {
      openModel();
    }
  }, [modelConfig,isCreateModalOpen]);
  useEffect(()=>{
    setAttendances(attendance)
  },[attendance])
  useEffect( () =>
  {
    dispatch(setProjectId(projects[0]?.id))
  },[projects])
 
  return (
    <>
    {isCreateModalOpen && modelConfig && (
       <div
       className="modal fade show"
       style={{ display: "block" }}
       id="check-Out-modal"
       tabindex="-1"
       aria-hidden="true"
      > 
        <AttendanceModel modelConfig={modelConfig} closeModal={closeModal} handleSubmitForm={handleSubmit}/>
        </div>
    )}
    
    <div className="container-xxl flex-grow-1 container-p-y">
      <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Attendance", link: null },
          ]}
      ></Breadcrumb> 
      <div class="nav-align-top nav-tabs-shadow">
      <ul class="nav nav-tabs" role="tablist">
      <div
         className="dataTables_length text-start py-2 px-2"
         id="DataTables_Table_0_length"
         >
        {
             ((loginUser && loginUser?.projects.length > 1) ) && (<label>
              <select                
                name="DataTables_Table_0_length"
                aria-controls="DataTables_Table_0"
                className="form-select form-select-sm"
                value={selectedProject}
                onChange={(e)=>dispatch(setProjectId(e.target.value))}
                aria-label=""
              >
                  {!projectLoading && projects?.filter(project =>
                    loginUser?.projects?.map(Number).includes(project.id)).map((project)=>(
                     <option value={project.id}>{project.name}</option>
                  ))} 
                 {projectLoading && <option value="Loading..." disabled>Loading...</option>  }
              </select>
            </label>)   
        }
        </div>   
      </ul>
         <ul class="nav nav-tabs" role="tablist">
    <li class="nav-item">
      <button
        type="button"
        class="nav-link active"
        role="tab"
        data-bs-toggle="tab"
        data-bs-target="#navs-top-home"
        aria-controls="navs-top-home"
        aria-selected="true">
        All
      </button>
    </li>
    <li class="nav-item">
      <button
        type="button"
        class="nav-link"
        role="tab"
        data-bs-toggle="tab"
        data-bs-target="#navs-top-profile"
        aria-controls="navs-top-profile"
        aria-selected="false">
        Logs
      </button>
    </li>
  
            <li className={`nav-item ${!DoRegularized && 'd-none'}`}>
              <button
                type="button"
                className="nav-link "
                role="tab"
                data-bs-toggle="tab"
                data-bs-target="#navs-top-messages"
                aria-controls="navs-top-messages"
                aria-selected="false">
                Regularization
              </button>
             
            </li>
          
         </ul>
          <div class="tab-content attedanceTabs py-2">
          {projectLoading && (<span>Loading..</span>)}
          {(!projectLoading && !attendances)  && <span>Not Found</span>}
          { (projects && projects.length > 0 ) && (
            <>
                <div className="tab-pane fade show active py-0" id="navs-top-home" role="tabpanel" key={projects.id}>   
                  
              <Attendance attendance={attendances} handleModalData={handleModalData} getRole={getRole} />
               </div>
               <div class="tab-pane fade" id="navs-top-profile" role="tabpanel">
                 
                 <AttendanceLog 
                   attendance={attendances}
                   handleModalData={handleModalData} 
                   projectId={selectedProject}
                 />
               </div>
               <div className="tab-pane fade" id="navs-top-messages" role="tabpanel">
                 <Regularization
                   attendance={attendances}
                   handleRequest ={handleSubmit}
                 />
               </div>
               </>
          )}
        </div>
      </div>
      

      </div>
    </>
  );
};

export default AttendancePage;
