import { useMutation } from "@apollo/client/react";
import { Dropdown, Spin } from "antd";
import { useState } 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 { selectBodyshop } from "../../redux/user/user.selectors";
import AuditTrailMapping from "../../utils/AuditTrailMappings";

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

export function ProductionListColumnStatus({ record, bodyshop, insertAuditTrail }) {
  const [updateJob] = useMutation(UPDATE_JOB);
  const [loading, setLoading] = useState(false);

  const handleSetStatus = async (e) => {
    if (
      bodyshop.md_ro_statuses.production_statuses.includes(record.status) &&
      !bodyshop.md_ro_statuses.post_production_statuses.includes(record.status)
    ) {
      logImEXEvent("production_change_status");
      //    e.stopPropagation();
      setLoading(true);
      const { key } = e;
      await updateJob({
        variables: {
          jobId: record.id,
          job: {
            status: key
          }
        }
      });
      insertAuditTrail({
        jobid: record.id,
        operation: AuditTrailMapping.jobstatuschange(key),
        type: "jobstatuschange"
      });
      setLoading(false);
    }
  };

  const menu = {
    items: bodyshop.md_ro_statuses.production_statuses.map((item) => ({
      key: item,
      label: item
    })),
    onClick: handleSetStatus,
    style: {
      maxHeight: "200px",
      overflowY: "auto"
    }
  };

  return (
    <Dropdown menu={menu} trigger={["click"]}>
      <div style={{ width: "100%", height: "19px", cursor: "pointer" }}>
        {record.status}
        {loading && <Spin />}
      </div>
    </Dropdown>
  );
}

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