import { DownCircleFilled } from "@ant-design/icons";
import { useMutation } from "@apollo/client/react";
import { Button, Dropdown } from "antd";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { UPDATE_JOB_STATUS } from "../../graphql/jobs.queries";
import { insertAuditTrail } from "../../redux/application/application.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

export function JobsAdminStatus({ insertAuditTrail, bodyshop, job }) {
  const { t } = useTranslation();
  const notification = useNotification();

  const [mutationUpdateJobstatus] = useMutation(UPDATE_JOB_STATUS);
  const updateJobStatus = (status) => {
    mutationUpdateJobstatus({
      variables: { jobId: job.id, status: status }
    })
      .then(() => {
        notification.success({ title: t("jobs.successes.save") });
        insertAuditTrail({
          jobid: job.id,
          operation: AuditTrailMapping.admin_jobstatuschange(status),
          type: "admin_jobstatuschange"
        });
        // refetch();
      })
      .catch(() => {
        notification.error({ title: t("jobs.errors.saving") });
      });
  };

  const statusMenu = {
    items: bodyshop.md_ro_statuses.statuses.map((item) => ({
      key: item,
      label: item
    })),
    onClick: (e) => {
      updateJobStatus(e.key);
    }
  };

  return (
    <Dropdown menu={statusMenu} trigger={["click"]} key="changestatus">
      <Button icon={<DownCircleFilled />} iconPlacement="end" shape="round">
        <span>{job.status}</span>
      </Button>
    </Dropdown>
  );
}
