import { useState, useEffect } from "react";
import EmployeeList from "./EmployeeList";
import { useAllEmployees } from "../../hooks/useEmployees";
import showToast from "../../services/toastService";
import { DirectoryRepository } from "../../repositories/DirectoryRepository";
import { useAssignEmpToBucket } from "../../hooks/useDirectory";

const AssignedBucket = ({ selectedBucket, handleClose }) => {
  const { employeesList } = useAllEmployees(false);
  const [selectedEmployees, setSelectedEmployees] = useState([]);

  useEffect(() => {
    if (selectedBucket) {
      const preselected = employeesList
        .filter((emp) => selectedBucket?.employeeIds?.includes(emp.employeeId))
        .map((emp) => ({ ...emp, isActive: true }));

      setSelectedEmployees(preselected);
    }
  }, [selectedBucket, employeesList]);

  const { mutate: AssignEmployee, isPending } = useAssignEmpToBucket(() =>
    handleClose()
  );

  const handleSubmit = async (e) => {
    e.preventDefault();

    const existingEmployeeIds = selectedBucket?.employeeIds || [];

    const employeesToUpdate = selectedEmployees.filter((emp) => {
      const isExisting = existingEmployeeIds.includes(emp.employeeId);
      return (!isExisting && emp.isActive) || (isExisting && !emp.isActive);
    });

    if (employeesToUpdate.length === 0) {
      showToast("No changes to update", "info");
      return;
    }

    AssignEmployee({
      bucketId: selectedBucket.id,
      EmployeePayload: employeesToUpdate.map((emp) => ({
        employeeId: emp.employeeId,
        isActive: emp.isActive,
      })),
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <EmployeeList
        employees={employeesList}
        bucket={selectedBucket}
        selectedEmployees={selectedEmployees}
        onChange={setSelectedEmployees}
      />

      <div className="mt-3 d-flex justify-content-end gap-3">
        <button type="submit" className="btn btn-sm btn-primary" disabled={isPending}>
         {isPending ? "Please Wait...":"Assign"}
        </button>
      </div>
    </form>
  );
};

export default AssignedBucket;
