import { ExclamationCircleFilled } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Dropdown } from "antd";
import React from "react";
import { useTranslation } from "react-i18next";
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";

const mapStateToProps = createStructuredSelector({});

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

export function ProductionListColumnAlert({ record, insertAuditTrail }) {
  const { t } = useTranslation();

  const [updateAlert] = useMutation(UPDATE_JOB);

  const handleAlertToggle = (e) => {
    logImEXEvent("production_toggle_alert");
    //e.stopPropagation();
    updateAlert({
      variables: {
        jobId: record.id,
        job: {
          production_vars: {
            ...record.production_vars,
            alert: !!record.production_vars && !!record.production_vars.alert ? !record.production_vars.alert : true
          }
        }
      }
    });
    insertAuditTrail({
      jobid: record.id,
      operation: AuditTrailMapping.alertToggle(
        !!record.production_vars && !!record.production_vars.alert ? !record.production_vars.alert : true
      ),
      type: "alertToggle"
    }).then(() => {
      if (record.refetch) record.refetch();
    });
  };

  const menu = {
    items: [
      {
        key: "toggleAlert",
        label:
          record.production_vars && record.production_vars.alert
            ? t("production.labels.alertoff")
            : t("production.labels.alerton"),
        onClick: handleAlertToggle
      }
    ]
  };

  return (
    <Dropdown menu={menu} trigger={["contextMenu"]}>
      <div
        style={{
          //width: "100%",
          height: "19px"
        }}
      >
        {record.production_vars && record.production_vars.alert ? (
          <ExclamationCircleFilled className="production-alert" />
        ) : null}
      </div>
    </Dropdown>
  );
}

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