import React, { useState } from "react";
import AllocationsBulkAssignment from "./allocations-bulk-assignment.component";
import { useMutation } from "@apollo/client";
import { INSERT_ALLOCATION } from "../../graphql/allocations.queries";
import { useTranslation } from "react-i18next";
import { notification } from "antd";

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 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((r) => {
      notification["success"]({
        message: 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}
    />
  );
}
