import { DownCircleFilled } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Button, Dropdown, Menu, notification } from "antd";
import React from "react";
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";

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

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

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

  const statusmenu = (
    <Menu
      onClick={(e) => {
        updateJobStatus(e.key);
      }}
    >
      {bodyshop.md_ro_statuses.statuses.map((item) => (
        <Menu.Item key={item}>{item}</Menu.Item>
      ))}
    </Menu>
  );

  return (
    <Dropdown overlay={statusmenu} trigger={["click"]} key="changestatus">
      <Button shape="round">
        <span>{job.status}</span>

        <DownCircleFilled />
      </Button>
    </Dropdown>
  );
}
