import React, { useState, useEffect } from "react";
import moment from "moment";
import { Link, NavLink, useNavigate } from "react-router-dom";
import Avatar from "../../components/common/Avatar";
import Breadcrumb from "../../components/common/Breadcrumb";
import ManageEmp from "../../components/Employee/ManageRole";
import {useEmployeesAllOrByProjectId} from "../../hooks/useEmployees";
import {  useProjects } from "../../hooks/useProjects";
import { useProfile } from "../../hooks/useProfile";
import {hasUserPermission} from "../../utils/authUtils";
import {MANAGE_EMPLOYEES} from "../../utils/constants";
import {useHasUserPermission} from "../../hooks/useHasUserPermission";

const EmployeeList = () =>
{
  const {profile:loginUser}= useProfile()
  const [selectedProject, setSelectedProject] = useState(""); 
  const {projects, loading: projectLoading} = useProjects()
  const ManageEmployee = useHasUserPermission(MANAGE_EMPLOYEES)

  const {employees, loading,setLoading, error} = useEmployeesAllOrByProjectId( selectedProject );
  const [ projectsList, setProjectsList ] = useState(projects ||  [] );
 
  const [employeeList,setEmployeeList] = useState([])
  const [modelConfig, setModelConfig] = useState();
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(5);
  const [isCreateModalOpen, setIsCreateModalOpen ] = useState( false );
  const [searchText,setSearchText] = useState("")
  const [filteredData, setFilteredData] = useState([]);
  const navigate = useNavigate()


  const handleSearch = (e) => {
    const value = e.target.value.toLowerCase();
    setSearchText(value);
  
    if (!employeeList.length) return;
  
    const results = employeeList.filter((item) =>
      Object.values(item).some((field) => 
        field && field.toString().toLowerCase().includes(value) 
      )
    );
  
    setFilteredData(results);
  };

 
  useEffect(() => {
    setCurrentPage( 1 )                                        
 
    if (!loading && Array.isArray(employees)) {
      setEmployeeList(employees);
      setFilteredData( employees );
    }
    
  }, [loading, employees, selectedProject]);
  

  const displayData = searchText ? filteredData : employeeList
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems =   Array.isArray(displayData)
  ? displayData.slice(indexOfFirstItem, indexOfLastItem)
    : [];
  
  const paginate = (pageNumber) => setCurrentPage(pageNumber);
  const totalPages = Array.isArray(displayData)
    ? Math.ceil(displayData.length / itemsPerPage)
    : 0;

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

    const closeModal = () => {
      setIsCreateModalOpen(false);
  
      const modalElement = document.getElementById("managerole-modal");
      if (modalElement) {
        modalElement.classList.remove("show");
        modalElement.style.display = "none";
        document.body.classList.remove("modal-open");
        document.querySelector(".modal-backdrop").remove();
      }
    };
  
    const handleConfigData = (config) => {
      setModelConfig(config);
    };
  
    useEffect(() => {
      if (modelConfig !== null) {
        openModal();
      }
    }, [ modelConfig, isCreateModalOpen ] );
  

  return (
    <>
      {isCreateModalOpen && (
        <ManageEmp employeeId={modelConfig} onClosed={closeModal} />
      )}
      <div className="container-xxl flex-grow-1 container-p-y">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Employees", link: null },
          ]}
        ></Breadcrumb>
        <div className="row">
          <div className="card ">
            <div className="card-datatable table-responsive pt-2">
              <div
                id="DataTables_Table_0_wrapper"
                className="dataTables_wrapper dt-bootstrap5 no-footer"
                style={{ width: "98%" }}
              >
                <div className="row  mb-2 ">
                  <div className="col-md-3 col-sm-6 ">
                    <div className="ms-0">
                      <div
                        className="dataTables_length text-start"
                        id="DataTables_Table_0_length"
                      >
                          <label>
                          <select
                               id="project-select"
                               onChange={(e)=>setSelectedProject(e.target.value)}
                               name="DataTables_Table_0_length"
                               aria-controls="DataTables_Table_0"
                               className="form-select form-select-sm"
                               value={selectedProject || ""}
                            >
                           {projectLoading ? (
                            <option value="Loading" >
                                   Loading...
                             </option>
                          ) : (
                         <>
                                <option value="">All Employees</option>
                                {Array.isArray(projects) && projects.map((item) => (
                                  <option key={item.id} value={item.id}>
                                             {item.name}
                                  </option>
                                ))}
                         </>
                          )}
                          </select>
                          </label>
                       
                      </div>
                    </div>
                  </div>
                  <div className="col-md-9 col-sm-6">
                    <div className="dt-action-buttons text-xl-end text-lg-start text-md-end text-start d-flex align-items-center justify-content-sm-end justify-content-between gap-2 flex-md-row flex-sm-column mb-3 mb-md-0 mt-1 mt-md-0 gap-md-4">
                      <div
                        id="DataTables_Table_0_filter"
                        className="dataTables_filter"
                      >
                        <label>
                          <input
                            type="search"
                            value={searchText}
                            onChange={handleSearch}
                            className="form-control form-control-sm"
                            placeholder="Search User"
                            aria-controls="DataTables_Table_0"
                          ></input>
                        </label>
                      </div>
                      <div className="dt-buttons btn-group flex-wrap">
                        {" "}
                        <div className=" d-flex justify-contend-end">
                          <button
                            aria-label="Click me"
                            className="btn btn-sm  btn-label-secondary me-4  dropdown-toggle "
                            type="button"
                            data-bs-toggle="dropdown"
                            aria-expanded="false"
                          >
                            <i className="bx bx-export me-2 bx-sm"></i>Export
                          </button>
                          <ul className="dropdown-menu">
                            <li>
                              <a
                                aria-label="dropdown item action"
                                className="dropdown-item"
                                href="#"
                              >
                                <i className="bx bx-printer me-1"></i>
                                Print
                              </a>
                            </li>
                            <li>
                              <a
                                aria-label="dropdown item another action"
                                className="dropdown-item"
                                href="#"
                              >
                                <i className="bx bx-file me-1"></i>
                                Csv
                              </a>
                            </li>
                            <li>
                              <a
                                aria-label="dropdown item something else here"
                                className="dropdown-item"
                                href="#"
                              >
                                <i className="bx bxs-file-export me-1"></i>
                                Excel
                              </a>
                            </li>

                            <li>
                              <a className="dropdown-item" href="#">
                                <i className="bx bxs-file-pdf me-1"></i>
                                Pdf
                              </a>
                            </li>
                          </ul>
                          <button
                        
                        className={`btn btn-sm add-new btn-primary ${!ManageEmployee && 'd-none'}`}
                            tabIndex="0"
                            type="button"
                          >
                            <span>
                              <Link
                                to="/employee/manage"
                                className="dropdown-item"
                              >
                                <i className="bx bx-plus-circle me-2"></i>
                                <span className="d-none d-md-inline-block">
                                  Add New Employee
                                </span>
                              </Link>
                            </span>
                          </button>{" "}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <table
                  className="datatables-users table border-top dataTable no-footer dtr-column "
                  id="DataTables_Table_0"
                  aria-describedby="DataTables_Table_0_info"
                  style={{ width: "100%" }}
                >
                  <thead>
                    <tr>
                      <th
                        className="sorting sorting_desc"
                        tabIndex="0"
                        aria-controls="DataTables_Table_0"
                        rowSpan="1"
                        colSpan="2"
                        aria-label="User: activate to sort column ascending"
                        aria-sort="descending"
                      >
                        Name
                      </th>
                      <th
                        className="sorting sorting_desc  d-none  d-sm-table-cell"
                        tabIndex="0"
                        aria-controls="DataTables_Table_0"
                        rowSpan="1"
                        colSpan="1"
                        aria-label="User: activate to sort column ascending"
                        aria-sort="descending"
                      >
                        Contact
                      </th>
                      <th
                        className="sorting sorting_desc  d-none  d-sm-table-cell"
                        tabIndex="0"
                        aria-controls="DataTables_Table_0"
                        rowSpan="1"
                        colSpan="1"
                        aria-label="User: activate to sort column ascending"
                        aria-sort="descending"
                      >
                        Role
                      </th>
                     
                      <th
                        className="sorting  d-none  d-md-table-cell"
                        tabIndex="0"
                        aria-controls="DataTables_Table_0"
                        rowSpan="1"
                        colSpan="1"
                        aria-label="Plan: activate to sort column ascending"
                      >
                        Joining Date
                      </th>
                      <th
                        className="sorting"
                        tabIndex="0"
                        aria-controls="DataTables_Table_0"
                        rowSpan="1"
                        colSpan="1"
                        aria-label="Billing: activate to sort column ascending"
                      >
                        Status
                      </th>
                      <th
                        className={`sorting_disabled  ${!ManageEmployee && 'd-none'}`}
                        rowSpan="1"
                        colSpan="1"
                        style={{ width: "50px" }}
                        aria-label="Actions"
                      >
                        Actions
                      </th>
                    </tr>
                  </thead>
                  <tbody> 
                    {loading &&  <tr>
                        <td colSpan={8}>
                          <p>Loading...</p>
                        </td>
                      </tr>}
                    {( !loading && employeeList?.length === 0 ) && <td colSpan={8}>Not Data Found </td>}
                    {( !loading && employeeList && currentItems.length === 0 && employeeList.length !==0 ) && <td colSpan={8}><small className="muted">'{searchText}' employee not found</small> </td>}
              
                    {(currentItems && !loading) && currentItems.sort((a, b) => b.id - a.id).map((item) => (
                      <tr className="odd" key={item.id}>
                        <td className="sorting_1" colSpan={2}>
                          <div className="d-flex justify-content-start align-items-center user-name">
                            <Avatar
                              firstName={item.firstName}
                              lastName={item.lastName}
                            ></Avatar>
                            <div className="d-flex flex-column">
                              <a
                             
                                onClick={()=>navigate(`/employee/${item.id}?for=account`)}
                                className="text-heading text-truncate cursor-pointer"
                              >
                                <span className="fw-medium">
                                  {item.firstName} {item.lastName}
                                </span>
                              </a>
                            </div>
                          </div>
                        </td>
                        <td className="text-start  d-none  d-sm-table-cell">
                          <span className="text-truncate">
                            <i className="bx bxs-phone-call text-primary me-2"></i>
                            {item.phoneNumber}
                          </span>
                        </td>
                        <td className=" d-none  d-sm-table-cell text-start">
                          <span className="text-truncate">
                            <i className="bx bxs-wrench text-success  me-2"></i>{item.jobRole || "Not Assign Yet"}
                          </span>
                        </td>
                      
                        <td className=" d-none  d-md-table-cell">
                          {moment(item.joiningDate).format("DD-MMM-YYYY")}
                        </td>
                        <td>
                          <span
                            className="badge bg-label-success"
                            text-capitalized=""
                          >
                            Active
                          </span>
                        </td>
                        <td className={`d-flex justify-content-end justify-content-sm-center ${!ManageEmployee && 'd-none'} `}>
                          <div className="d-flex align-items-center ">
                            <a
                              className={`btn btn-icon dropdown-toggle hide-arrow`}
                              data-bs-toggle="dropdown"
                            >
                              <i className="bx bx-dots-vertical-rounded bx-md"></i>
                            </a>

                            <div className="dropdown-menu dropdown-menu-end m-0">
                              {" "}
                              <a
                               
                                onClick={()=> navigate(`/employee/${item.id}`)}
                                className="dropdown-item"
                              >
                                View
                              </a>

                              <Link
                                className={`dropdown-item `}
                                to={`/employee/manage/${item.id}`}
                              >
                                Edit
                              </Link>
                             
                              <a  className="dropdown-item">
                                Suspend
                              </a>
                              <a
                                className="dropdown-item"
                                type="button"
                                data-bs-toggle="modal"
                                data-bs-target="#managerole-modal"
                                onClick={() => {
                                  handleConfigData(item.id);
                                }}
                              >
                                Manage Role
                              </a>
                            </div>
                          </div>
                        </td>
                      </tr>
                    ) )}
                    
                  </tbody>
                </table>

                <div style={{ width: "1%" }}></div>

                {/* Pagination */}
                {!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>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default EmployeeList;
