import React, { useState, useEffect, useCallback } from "react";
import MapUsers from "./MapUsers";
import { Link, NavLink, useNavigate, useParams } from "react-router-dom";

import showToast from "../../services/toastService";
import Avatar from "../common/Avatar";
import moment from "moment";

import ProjectRepository from "../../repositories/ProjectRepository";
import { useDispatch, useSelector } from "react-redux";
import { changeMaster } from "../../slices/localVariablesSlice";
import useMaster from "../../hooks/masterHook/useMaster";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { ASSIGN_TO_PROJECT } from "../../utils/constants";
import ConfirmModal from "../common/ConfirmModal";
import eventBus from "../../services/eventBus";
import {
  useEmployeesByProjectAllocated,
  useManageProjectAllocation,
  useProjectAssignedServices,
} from "../../hooks/useProjects";
import { useSelectedProject } from "../../slices/apiDataManager";

const Teams = () => {
  const projectId = useSelectedProject();
  const dispatch = useDispatch();

  const { data, loading } = useMaster();
  const [isModalOpen, setIsModelOpen] = useState(false);
  const [error, setError] = useState("");
  const [empJobRoles, setEmpJobRoles] = useState(null);
  const [employees, setEmployees] = useState([]);
  const [filteredEmployees, setFilteredEmployees] = useState([]);
  const [removingEmployeeId, setRemovingEmployeeId] = useState(null);
  const [assignedLoading, setAssignedLoading] = useState(false);
  const [activeEmployee, setActiveEmployee] = useState(true);
  const [deleteEmployee, setDeleteEmplyee] = useState(null);
  const [searchTerm, setSearchTerm] = useState(""); // State for search term
  const [selectedService, setSelectedService] = useState(null);

  const { data: assignedServices, isLoading: servicesLoading } = useProjectAssignedServices(projectId);
  const handleToggleActive = e => setActiveEmployee(e.target.checked);


  const handleServiceChange = (e) => {
    setSelectedService(e.target.value);
  };

  const navigate = useNavigate();

  const HasAssignUserPermission = useHasUserPermission(ASSIGN_TO_PROJECT);
  const [IsDeleteModal, setIsDeleteModal] = useState(false);
  const {
    projectEmployees,
    loading: employeeLodaing,
    refetch,
  } = useEmployeesByProjectAllocated(projectId,selectedService);
  const {
    mutate: submitAllocations,
    isPending,
    isSuccess,
    isError,
  } = useManageProjectAllocation({
    onSuccessCallback: () => {
      setRemovingEmployeeId(null);
      setAssignedLoading(false);
      setDeleteEmplyee(null);
      closeDeleteModal();
    },
    onErrorCallback: () => {
      closeDeleteModal();
    },
  });

  const removeAllocation = (item) => {
    setRemovingEmployeeId(item.id);

    submitAllocations({
      items: [
        {
          empID: item.employeeId,
          jobRoleId: item.jobRoleId,
          projectId: projectId,
          status: false,
        },
      ],
      added: false,
    });
  };

  const handleEmpAlicationFormSubmit = (allocaionObj) => {
    let items = allocaionObj.map((item) => {
      return {
        empID: item.empID,
        jobRoleId: item.jobRoleId,
        projectId: projectId,
        status: true,
      };
    });

    submitAllocations({ items, added: true });

    setActiveEmployee(true);
    setFilteredEmployees(employees.filter((emp) => emp.isActive));

    const dropdown = document.querySelector(
      'select[name="DataTables_Table_0_length"]'
    );
    if (dropdown) dropdown.value = "true";
  };

  const getRole = (jobRoleId) => {
    if (loading) return "Loading...";
    if (!Array.isArray(empJobRoles)) return "Unassigned";
    if (!jobRoleId) return "Unassigned";

    const role = empJobRoles.find((b) => b.id == jobRoleId);
    return role ? role.name : "Unassigned";
  };
  const openModel = () => {
    setIsModelOpen(true);
  };

  const onModelClose = () => {
    setIsModelOpen(false);
    const modalElement = document.getElementById("user-model");
    if (modalElement) {
      modalElement.classList.remove("show");
      modalElement.style.display = "none";
      document.body.classList.remove("modal-open");
      document.querySelector(".modal-backdrop").remove();
    }
    const modalBackdropElement = document.querySelector(".modal-backdrop");
    if (modalBackdropElement) {
      modalBackdropElement.remove();
    }
    document.body.style.overflow = "auto";
  };

  useEffect(() => {
    dispatch(changeMaster("Job Role"));
  }, [dispatch]);

  useEffect(() => {
    if (projectEmployees) {
      setEmployees(projectEmployees);
      const filtered = projectEmployees.filter((emp) => emp.isActive);
      setFilteredEmployees(filtered);
    }
  }, [projectEmployees, employeeLodaing]);

  useEffect(() => {
    if (data) {
      setEmpJobRoles(data);
    }
  }, [data]);
const filterAndSearchEmployees = useCallback(() => {
  const statusFiltered = employees.filter((emp) =>
    activeEmployee ? emp.isActive : !emp.isActive
  );

  if (searchTerm === "") {
    setFilteredEmployees(statusFiltered);
    return;
  }

  const lowercasedSearchTerm = searchTerm.toLowerCase();

  const searchedAndFiltered = statusFiltered.filter((item) => {
    const fullName = `${item.firstName} ${item.middleName} ${item.lastName}`.toLowerCase();
    const roleName = getRole(item.jobRoleId).toLowerCase();
    const orgName = (item.organizationName || "").toLowerCase();
    const serviceName = (item.serviceName || "").toLowerCase();

    return (
      fullName.includes(lowercasedSearchTerm) ||
      roleName.includes(lowercasedSearchTerm) ||
      orgName.includes(lowercasedSearchTerm) ||
      serviceName.includes(lowercasedSearchTerm)
    );
  });

  setFilteredEmployees(searchedAndFiltered);
}, [employees, activeEmployee, searchTerm, getRole]);


  useEffect(() => {
    filterAndSearchEmployees();
  }, [employees, activeEmployee, searchTerm, filterAndSearchEmployees]);

  const handleFilterEmployee = (e) => {
    const filterValue = e.target.value;
    setActiveEmployee(filterValue === "true");
    setSearchTerm("");
  };

  const handleSearch = (e) => {
    setSearchTerm(e.target.value);
  };

  const deleteModalOpen = (item) => {
    setDeleteEmplyee(item);
    setIsDeleteModal(true);
  };
  const closeDeleteModal = () => setIsDeleteModal(false);

  const handler = useCallback(
    (msg) => {
      if (msg.projectIds.some((item) => item === projectId)) {
        refetch();
      }
    },
    [projectId, refetch]
  );

  useEffect(() => {
    eventBus.on("assign_project_all", handler);
    return () => eventBus.off("assign_project_all", handler);
  }, [handler]);

  const employeeHandler = useCallback(
    (msg) => {
      if (filteredEmployees.some((item) => item.employeeId == msg.employeeId)) {
        refetch();
      }
    },
    [filteredEmployees, refetch]
  );

  useEffect(() => {
    eventBus.on("employee", employeeHandler);
    return () => eventBus.off("employee", employeeHandler);
  }, [employeeHandler]);

  return (
    <>
      <div
        className="modal fade"
        id="user-model"
        tabIndex="-1"
        aria-labelledby="userModalLabel"
        aria-hidden="true"
      >
        <MapUsers
          projectId={projectId}
          onClose={onModelClose}
          empJobRoles={empJobRoles}
          onSubmit={handleEmpAlicationFormSubmit}
          allocation={employees}
          assignedLoading={assignedLoading}
          setAssignedLoading={setAssignedLoading}
        ></MapUsers>
      </div>

      {IsDeleteModal && (
        <ConfirmModal
          isOpen={IsDeleteModal}
          type="delete"
          header="Removed Employee"
          message="Are you sure you want delete?"
          onSubmit={() => removeAllocation(deleteEmployee)}
          onClose={closeDeleteModal}
          loading={isPending}
        />
      )}

      <div className="card card-action mb-6">
        <div className="card-body">
          <div className="row d-flex justify-content-between mb-4">
            <div className="col-md-6 col-12 d-flex align-items-center">
              <div className="dataTables_length text-start py-1 px-0 col-md-4 col-12">
                {servicesLoading ? null : assignedServices && assignedServices.length > 0 ? (
                  assignedServices.length > 1 ? (
                    <label>
                      <select
                        name="serviceFilter"
                        aria-controls="DataTables_Table_0"
                        className="form-select form-select-sm"
                        aria-label="Select Service"
                        value={selectedService}
                        onChange={handleServiceChange}
                        style={{ fontSize: "0.875rem", height: "32px", width: "190px" }}
                      >
                        <option value="">All Services</option>
                        {assignedServices.map((service) => (
                          <option key={service.id} value={service.id}>
                            {service.name}
                          </option>
                        ))}
                      </select>
                    </label>
                  ) : (
                    <div>
                      <h5>{assignedServices[0].name}</h5>
                    </div>
                  )
                ) : (
                  <div>
                    <h5>No Services Assigned</h5>
                  </div>
                )}
              </div>


            </div>
            <div className="col-md-6 col-12 d-flex justify-content-end align-items-center">
              <div className="form-check form-switch me-2 mt-2">
                <input
                  type="checkbox"
                  className="form-check-input"
                  checked={activeEmployee}
                  onChange={handleToggleActive}
                  id="activeEmployeeSwitch"
                />
                <label className="form-check-label ms-0 " htmlFor="activeEmployeeSwitch">
                  {activeEmployee ? "Active Employees" : "Inactive Employees"}
                </label>
              </div>
              <div className="dataTables_filter d-inline-flex align-items-center ms-2">
                <input
                  type="search"
                  className="form-control form-control-sm me-4"
                  placeholder="Search by Name or Role"
                  aria-controls="DataTables_Table_0"
                  value={searchTerm}
                  onChange={handleSearch}
                />
              </div>

              <button
                type="button"
                className={`link-button btn-primary btn-sm ${HasAssignUserPermission ? "" : "d-none"
                  }`}
                data-bs-toggle="modal"
                data-bs-target="#user-model"
              >
                <i className="bx bx-plus-circle me-2"></i>
                Assign Employee
              </button>
            </div>
          </div>
          <div className="table-responsive text-nowrap">
            {employeeLodaing && <p>Loading..</p>}
            {!employeeLodaing &&
              filteredEmployees &&
              filteredEmployees.length > 0 && (
                <table className="table ">
                  <thead>
                    <tr>
                      <th>
                        <div className="text-start ms-5">Name</div>
                      </th>
                      <th>Services</th>
                      <th>Organization</th>
                      <th>Assigned Date</th>
                      {!activeEmployee && <th>Release Date</th>}
                      <th>Project Role</th>
                      <th>Actions</th>
                    </tr>
                  </thead>
                  <tbody className="table-border-bottom-0">
                    {filteredEmployees &&
                      filteredEmployees.map((item) => (
                        <tr key={item.id}>
                          <td>
                            <div className="d-flex justify-content-start align-items-center">
                              <Avatar
                                firstName={item.firstName}
                                lastName={item.lastName}
                              />
                              <div className="d-flex flex-column">
                                <a
                                  onClick={() =>
                                    navigate(
                                      `/employee/${item.employeeId}?for=attendance`
                                    )
                                  }
                                  className="text-heading text-truncate cursor-pointer"
                                >
                                  <span className="fw-normal">
                                    {item.firstName} {item.middleName}{" "}
                                    {item.lastName}
                                  </span>
                                </a>
                              </div>
                            </div>
                          </td>

                          <td>{item.serviceName || "N/A"}</td>
                          <td>{item.organizationName || "N/A"}</td>

                          <td>
                            {moment(item.allocationDate).format("DD-MMM-YYYY")}
                          </td>
                          {!activeEmployee && (
                            <td>
                              {item.reAllocationDate
                                ? moment(item.reAllocationDate).format("DD-MMM-YYYY")
                                : "Present"}
                            </td>
                          )}
                          <td>
                            <span className="badge bg-label-primary me-1">
                              {getRole(item.jobRoleId)}
                            </span>
                          </td>
                          <td>
                            {item.isActive ? (
                              <button
                                aria-label="Delete"
                                type="button"
                                title="Remove from project"
                                className="btn p-0 dropdown-toggle hide-arrow"
                                onClick={() => deleteModalOpen(item)}
                              >
                                {removingEmployeeId === item.id ? (
                                  <div
                                    className="spinner-border spinner-border-sm text-primary"
                                    role="status"
                                  >
                                    <span className="visually-hidden">Loading...</span>
                                  </div>
                                ) : (
                                  <i className="bx bx-trash me-1 text-danger"></i>
                                )}
                              </button>
                            ) : (
                              <span>Not in project</span>
                            )}
                          </td>
                        </tr>
                      ))}
                  </tbody>
                </table>

              )}
            {!employeeLodaing && filteredEmployees.length === 0 && (
              <div className="text-center text-muted py-3">
                {activeEmployee
                  ? "No active employees assigned to the project"
                  : "No inactive employees assigned to the project"}
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default Teams;
