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";

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

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

  const handleSetStatus = async (e) => {
    logImEXEvent("production_change_status");

    setLoading(true);
    const { key } = e;
    await updateJob({
      variables: {
        jobId: record.id,
        job: {
          category: key
        }
      }
    });

    setLoading(false);
  };

  const menu = {
    items: bodyshop.md_categories.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.category}
        {loading && <Spin />}
      </div>
    </Dropdown>
  );
}

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