import { useMutation, useQuery } from "@apollo/client";
import { notification } from "antd";
import React, { useState } from "react";
//import SpinComponent from "../../components/loading-spinner/loading-spinner.component";
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";

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 handleNoteDelete = (id) => {
    logImEXEvent("job_note_delete");
    setDeleteLoading(true);
    deleteNote({
      variables: {
        noteId: id,
      },
    }).then((r) => {
      refetch();
      notification["success"]({
        message: t("notes.successes.deleted"),
      });
      insertAuditTrail({
        jobid: jobId,
        operation: AuditTrailMapping.jobnotedeleted(),
        type: "jobnotedeleted",
      });
    });
    setDeleteLoading(false);
  };

  //if (loading) return <SpinComponent />;
  if (error) return <AlertComponent message={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 && data.jobs_by_pk.vehicle.jobs : null
      }
      refetch={refetch}
      deleteLoading={deleteLoading}
      handleNoteDelete={handleNoteDelete}
      ro_number={data ? data.jobs_by_pk.ro_number : null}
    />
  );
}
