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

const mapStateToProps = createStructuredSelector({});
const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation, type }) => dispatch(insertAuditTrail({ jobid, operation, type }))
});

export default connect(mapStateToProps, mapDispatchToProps)(JobsAdminRemoveAR);

export function JobsAdminRemoveAR({ insertAuditTrail, job }) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [switchValue, setSwitchValue] = useState(job.remove_from_ar);
  const notification = useNotification();

  const [mutationUpdateRemoveFromAR] = useMutation(UPDATE_REMOVE_FROM_AR);

  const handleChange = async (value) => {
    setLoading(true);
    const result = await mutationUpdateRemoveFromAR({
      variables: { jobId: job.id, remove_from_ar: value }
    });

    if (!result.errors) {
      notification["success"]({ message: t("jobs.successes.save") });
      insertAuditTrail({
        jobid: job.id,
        operation: AuditTrailMapping.admin_job_remove_from_ar(value),
        type: "admin_job_remove_from_ar"
      });
      setSwitchValue(value);
    } else {
      notification["error"]({
        message: t("jobs.errors.saving", {
          error: JSON.stringify(result.errors)
        })
      });
    }
    setLoading(false);
  };

  return (
    <>
      <div style={{ display: "flex", alignItems: "center" }}>
        <div style={{ marginRight: "10px" }}>{t("jobs.labels.remove_from_ar")}:</div>
        <div>
          <Switch checked={switchValue} loading={loading} onChange={handleChange} />
        </div>
      </div>
    </>
  );
}
