import { useMutation, useQuery } from "@apollo/client/react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import AlertComponent from "../../components/alert/alert.component";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { DELETE_NOTE, QUERY_NOTES_BY_JOB_PK } from "../../graphql/notes.queries";
import { insertAuditTrail } from "../../redux/application/application.actions";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import JobNotesComponent from "./jobs.notes.component";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
});
const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation, type }) => dispatch(insertAuditTrail({ jobid, operation, type }))
});
export default connect(mapStateToProps, mapDispatchToProps)(JobNotesContainer);

export function JobNotesContainer({ jobId, insertAuditTrail }) {
  const { loading, error, data, refetch } = useQuery(QUERY_NOTES_BY_JOB_PK, {
    variables: { id: jobId },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  const [deleteNote] = useMutation(DELETE_NOTE);
  const { t } = useTranslation();
  const [deleteLoading, setDeleteLoading] = useState(false);
  const notification = useNotification();

  const handleNoteDelete = (id) => {
    logImEXEvent("job_note_delete");
    setDeleteLoading(true);
    deleteNote({
      variables: {
        noteId: id
      }
    }).then(() => {
      refetch();
      notification.success({
        title: t("notes.successes.deleted")
      });
      insertAuditTrail({
        jobid: jobId,
        operation: AuditTrailMapping.jobnotedeleted(),
        type: "jobnotedeleted"
      });
    });
    setDeleteLoading(false);
  };

  //if (loading) return <SpinComponent />;
  if (error) return <AlertComponent title={error.message} type="error" />;
  return (
    <JobNotesComponent
      jobId={jobId}
      loading={loading}
      data={data ? data.jobs_by_pk.notes : null}
      relatedRos={data ? data.jobs_by_pk.vehicle?.jobs : null}
      refetch={refetch}
      deleteLoading={deleteLoading}
      handleNoteDelete={handleNoteDelete}
      ro_number={data ? data.jobs_by_pk.ro_number : null}
    />
  );
}
