import { useState } from "react";
import AllocationsBulkAssignment from "./allocations-bulk-assignment.component";
import { useMutation } from "@apollo/client/react";
import { INSERT_ALLOCATION } from "../../graphql/allocations.queries";
import { useTranslation } from "react-i18next";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

export default function AllocationsBulkAssignmentContainer({ jobLines, refetch }) {
  const visibilityState = useState(false);
  const { t } = useTranslation();
  const [assignment, setAssignment] = useState({
    employeeid: null
  });
  const [insertAllocation] = useMutation(INSERT_ALLOCATION);
  const notification = useNotification();

  const handleAssignment = () => {
    const allocs = jobLines.reduce((acc, value) => {
      acc.push({
        joblineid: value.id,
        hours: parseFloat(value.mod_lb_hrs) || 0,
        employeeid: assignment.employeeid
      });
      return acc;
    }, []);

    insertAllocation({ variables: { alloc: allocs } }).then(() => {
      notification.success({
        title: t("employees.successes.save")
      });
      visibilityState[1](false);
      if (refetch) refetch();
    });
  };

  return (
    <AllocationsBulkAssignment
      disabled={jobLines.length > 0 ? false : true}
      handleAssignment={handleAssignment}
      assignment={assignment}
      setAssignment={setAssignment}
      visibilityState={visibilityState}
    />
  );
}
