import { ExclamationCircleFilled, PlusCircleFilled } from "@ant-design/icons";
import { useMutation } from "@apollo/client/react";
import { Button, Popconfirm } from "antd";
import { useCallback } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { UPDATE_JOB } from "../../graphql/jobs.queries";
import { insertAuditTrail } from "../../redux/application/application.actions";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import { useTranslation } from "react-i18next";

const mapStateToProps = createStructuredSelector({});

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

const ProductionListColumnAlert = ({ id, productionVars, refetch, insertAuditTrail }) => {
  const [updateAlert] = useMutation(UPDATE_JOB);
  const { t } = useTranslation();

  const handleAlertToggle = useCallback(() => {
    logImEXEvent("production_toggle_alert");

    const newAlertState = productionVars?.alert ? !productionVars?.alert : true;
    const finalProductionVars = {
      ...productionVars,
      alert: newAlertState
    };

    updateAlert({
      variables: {
        jobId: id,
        job: {
          production_vars: finalProductionVars
        }
      }
    }).catch((err) => {
      console.error(`Something went wrong updating production note: ${err.message || ""}`);
    });

    insertAuditTrail({
      jobid: id,
      operation: AuditTrailMapping.alertToggle(newAlertState),
      type: "alertToggle"
    });

    if (refetch) refetch();
  }, [updateAlert, insertAuditTrail, id, productionVars, refetch]);

  return productionVars?.alert ? (
    <Popconfirm
      title={t("general.actions.remove_alert")}
      onConfirm={handleAlertToggle}
      okText={t("general.labels.yes")}
      cancelText={t("general.labels.no")}
    >
      <Button className="production-alert" icon={<ExclamationCircleFilled />} style={{ cursor: "pointer" }} />
    </Popconfirm>
  ) : (
    <Button className="muted-button" icon={<PlusCircleFilled />} onClick={handleAlertToggle} style={{ cursor: "pointer" }} />
  );
};

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