import React, { useState, useEffect } from "react";
import EmployeeRepository from "../../repositories/EmployeeRepository";
import AssignEmployeeCard from "./AssignEmployeeCard";
import {useAllEmployees} from "../../hooks/useEmployees";
import useSearch from "../../hooks/useSearch";

const MapUsers = ({
  projectId,
  onClose,
  empJobRoles,
  onSubmit,
  allocation,
}) => {
  const {employeesList, loading, 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 = () => {
    const selected = selectedEmployees
      .filter((emp) => emp.isSelected)
      .map((emp) => ({ empID: emp.id, jobRoleId: emp.jobRoleId }));
    onSubmit(selected);
  };

  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">
              <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">
            <ul className="list-group border-none mb-2">
              {loading && !employeesList && <p>Loading...</p>}
              {filteredData.map((emp) => (
                <AssignEmployeeCard
                  key={emp.id}
                  employee={emp}
                  jobRoles={empJobRoles}
                  isChecked={emp.isSelected} 
                  onRoleChange={handleRoleChange}
                  onCheckboxChange={handleCheckboxChange}
                />
              ) )}
              {filteredData.length == 0 && <p>No Data Found</p>}
            </ul>
          </div>
          <div className="modal-footer">
            <button className="btn btn-sm btn-success" onClick={handleSubmit}>
              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;