import React, { useState, useEffect } from "react";
import EmployeeRepository from "../../repositories/EmployeeRepository";
import { useAllEmployees } from "../../hooks/useEmployees";
import useSearch from "../../hooks/useSearch";
import AssignEmployeeTable from "./AssignEmployeeTable";
import showToast from "../../services/toastService";

const MapUsers = ({
  projectId,
  onClose,
  empJobRoles,
  onSubmit,
  allocation,
  assignedLoading,
  setAssignedLoading,
}) => {
  const { employeesList, loading: employeeLoading, error } = useAllEmployees();
  const [selectedEmployees, setSelectedEmployees] = useState([]);
  const [ searchText, setSearchText ] = useState( "" );

  const handleAllocationData = Array.isArray(allocation) ? allocation : [];

  const allocationEmployees = employeesList.map((employee) => {
    const allocationItem = handleAllocationData.find(
      (alloc) => alloc.employeeId === employee.id
    );
    return {
      ...employee,
      isActive: allocationItem ? allocationItem.isActive : false,
      jobRoleId: allocationItem ? allocationItem.jobRoleId : employee.jobRoleId,
    };
  });

  function parseDate(dateStr) {
    return new Date(dateStr.split(".")[0]);
  }

  const latestAllocations = handleAllocationData.reduce((acc, alloc) => {
    const existingAlloc = acc[alloc.employeeId];

    if (!existingAlloc) {
      acc[alloc.employeeId] = alloc;
    } else {
      const existingDate = parseDate(
        existingAlloc.reAllocationDate || existingAlloc.allocationDate
      );
      const newDate = parseDate(alloc.reAllocationDate || alloc.allocationDate);

      if (newDate > existingDate) {
        acc[alloc.employeeId] = alloc;
      }
    }
    return acc;
  }, {});

  const allocationEmployeesData = employeesList
    .map((employee) => {
      const allocationItem = latestAllocations[employee.id];
      return {
        ...employee,
        isActive: allocationItem ? allocationItem.isActive : false,
      };
    })
    .filter((employee) => employee.isActive === false);

  const { filteredData, setSearchQuery } = useSearch(
    allocationEmployeesData,
    searchText
  );

  const handleRoleChange = (employeeId, newRoleId) => {
    setSelectedEmployees((prevSelectedEmployees) =>
      prevSelectedEmployees.map((emp) =>
        emp.id === employeeId ? { ...emp, jobRoleId: newRoleId } : emp
      )
    );
  };

  const handleCheckboxChange = (employeeId) => {
    setSelectedEmployees((prevSelectedEmployees) => {
      const updatedEmployees = [...prevSelectedEmployees];
      const employeeIndex = updatedEmployees.findIndex(
        (emp) => emp.id === employeeId
      );

      if (employeeIndex !== -1) {
        const isSelected = !updatedEmployees[employeeIndex].isSelected;
        updatedEmployees[employeeIndex].isSelected = isSelected;
      } else {
        updatedEmployees.push({
          id: employeeId,
          isSelected: true,
        });
      }
      return updatedEmployees;
    });
  };

  const handleSubmit = () =>
  {
    setAssignedLoading(true)
    const selected = selectedEmployees
      .filter((emp) => emp.isSelected)
      .map((emp) => ({ empID: emp.id, jobRoleId: emp.jobRoleId }));
    if (selected.length > 0) {
      onSubmit(selected);
      setSelectedEmployees([]);
    } else {
      showToast("Please select Employee", "error");
    }

  };
  return (
    <>
      <div className="modal-dialog modal-dialog-scrollable mx-sm-auto mx-1 modal-lg modal-simple modal-edit-user">
        <div className="modal-content">
          <div className="modal-header">
            <div className="md-2 mb-1">
              {(filteredData.length > 0 ||
                  allocationEmployeesData.length > 0)&& (
                  <div className="input-group">
                    <input
                      type="search"
                      className="form-control form-control-sm"
                      placeholder="Search employees..."
                      onChange={(e) => setSearchQuery(e.target.value)}
                    />
                  </div>
                )}
            </div>
          </div>
          <div className="modal-body p-sm-4 p-0">
            <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></thead>
              <tbody>
                {employeeLoading && allocationEmployeesData.length === 0 && (
                  <p>Loading...</p>
                )}

                {!employeeLoading &&
                  allocationEmployeesData.length === 0 &&
                  filteredData.length === 0 && (
                    <p>All employee assigned to Project.</p>
                  )}

                {!employeeLoading && allocationEmployeesData.length > 0 && filteredData.length === 0 && (
                  <p>No matching employees found.</p>
                )}

                {(filteredData.length > 0 ||
                  allocationEmployeesData.length > 0) &&
                  filteredData.map((emp) => (
                    <AssignEmployeeTable
                      key={emp.id}
                      employee={emp}
                      jobRoles={empJobRoles}
                      isChecked={emp.isSelected}
                      onRoleChange={handleRoleChange}
                      onCheckboxChange={handleCheckboxChange}
                    />
                  ))}
              </tbody>
            </table>
          </div>
          <div className="modal-footer">
            {(filteredData.length > 0 ||
                  allocationEmployeesData.length > 0) && (
                <button
                  className="btn btn-sm btn-success"
                  onClick={handleSubmit}
                >
                  {assignedLoading ? "Please Wait...":"Assign to Project"}
                </button>
              )}

            <button
              type="button"
              className="btn btn-sm btn-secondary"
              data-dismiss="modal"
              aria-label="Close"
              onClick={onClose}
            >
              Cancel
            </button>
          </div>
        </div>
      </div>
    </>
  );
};

export default MapUsers;
