import { useState } from "react";
import AllocationsAssignmentComponent from "./allocations-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 AllocationsAssignmentContainer({ jobLineId, hours, refetch }) {
  const visibilityState = useState(false);
  const { t } = useTranslation();
  const [assignment, setAssignment] = useState({
    joblineid: jobLineId,
    hours: parseFloat(hours),
    employeeid: null
  });
  const [insertAllocation] = useMutation(INSERT_ALLOCATION);
  const notification = useNotification();

  const handleAssignment = () => {
    insertAllocation({ variables: { alloc: { ...assignment } } })
      .then(() => {
        notification.success({
          title: t("allocations.successes.save")
        });
        visibilityState[1](false);
        if (refetch) refetch();
      })
      .catch((error) => {
        notification.error({
          title: t("employees.errors.saving", { message: error.message })
        });
      });
  };

  return (
    <AllocationsAssignmentComponent
      handleAssignment={handleAssignment}
      maxHours={hours}
      assignment={assignment}
      setAssignment={setAssignment}
      visibilityState={visibilityState}
    />
  );
}
