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

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation }) =>
    dispatch(insertAuditTrail({ jobid, operation })),
});
export function ProductionListColumnStatus({
  record,
  bodyshop,
  insertAuditTrail,
}) {
  const [updateJob] = useMutation(UPDATE_JOB);
  const [loading, setLoading] = useState(false);

  const handleSetStatus = async (e) => {
    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),
    });

    setLoading(false);
  };

  return (
    <Dropdown
      overlay={
        <Menu
          style={{ maxHeight: "200px", overflowY: "auto" }}
          onClick={handleSetStatus}
        >
          {bodyshop.md_ro_statuses.production_statuses.map((item) => (
            <Menu.Item key={item}>{item}</Menu.Item>
          ))}
        </Menu>
      }
      trigger={["click"]}
    >
      <div style={{ width: "100%", height: "19px", cursor: "pointer" }}>
        {record.status}
        {loading && <Spin />}
      </div>
    </Dropdown>
  );
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ProductionListColumnStatus);
