import { useMutation } from "@apollo/client/react";
import { Button } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { UNVOID_JOB } from "../../graphql/jobs.queries";
import { insertAuditTrail } from "../../redux/application/application.actions";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

export function JobsAdminUnvoid({ insertAuditTrail, bodyshop, job, currentUser }) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [mutationUnvoidJob] = useMutation(UNVOID_JOB);
  const notification = useNotification();

  const handleUpdate = async () => {
    setLoading(true);
    const result = await mutationUnvoidJob({
      variables: {
        jobId: job.id,
        default_imported: bodyshop.md_ro_statuses.default_imported,
        currentUserEmail: currentUser.email,
        text: t("jobs.labels.unvoidnote")
      }
    });

    if (!result.errors) {
      notification.success({ title: t("jobs.successes.save") });

      insertAuditTrail({
        jobid: job.id,
        operation: AuditTrailMapping.admin_jobunvoid(),
        type: "admin_jobunvoid"
      });
    } else {
      notification.error({
        title: t("jobs.errors.saving", {
          error: JSON.stringify(result.errors)
        })
      });
    }
    setLoading(false);
    //Get the owner details, populate it all back into the job.
  };

  return (
    <Button loading={loading} disabled={!job.voided} onClick={handleUpdate}>
      {t("jobs.actions.unvoid")}
    </Button>
  );
}
