import { notification } from "antd";
import React, { useEffect, useState } from "react";
import { useMutation } from "react-apollo";
import { useTranslation } from "react-i18next";
import { INSERT_NEW_NOTE, UPDATE_NOTE } from "../../graphql/notes.queries";
import NoteUpsertModalComponent from "./note-upsert-modal.component";


import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectCurrentUser } from "../../redux/user/user.selectors";
const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser
});

export default connect (mapStateToProps,null)( function NoteUpsertModalContainer({
  jobId,
  visible,
  changeVisibility,
  refetch,
  existingNote,currentUser
}) {
  const { t } = useTranslation();
  const [insertNote] = useMutation(INSERT_NEW_NOTE);
  const [updateNote] = useMutation(UPDATE_NOTE);

  const [noteState, setNoteState] = useState({
    private: false,
    critical: false,
    text: ""
  });

  useEffect(() => {
    //Required to prevent infinite looping.
    if (existingNote) {
      setNoteState(existingNote);
    }
  }, [existingNote]);

  const insertNewNote = () => {
    insertNote({
      variables: {
        noteInput: [
          { ...noteState, jobid: jobId, created_by: currentUser.email } 
        ]
      }
    }).then(r => {
      refetch();
      changeVisibility(!visible);
      notification["success"]({
        message: t("notes.successes.create")
      });
    });
  };

  const updateExistingNote = () => {
    //Required, otherwise unable to spread in new note prop.
    delete noteState.__typename;
    updateNote({
      variables: {
        noteId: noteState.id,
        note: noteState
      }
    }).then(r => {
      notification["success"]({
        message: t("notes.successes.updated")
      });
    });
    refetch();
    changeVisibility(!visible);
  };

  return (
    <NoteUpsertModalComponent
      visible={visible}
      changeVisibility={changeVisibility}
      updateExistingNote={updateExistingNote}
      insertNewNote={insertNewNote}
      noteState={noteState}
      setNoteState={setNoteState}
    />
  );
}
);
