import { useMutation } from "@apollo/client/react";
import { UPDATE_JOB } from "../../graphql/jobs.queries";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { Dropdown } from "antd";
import { DownOutlined } from "@ant-design/icons";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({});

export function JobAltTransportChange({ bodyshop, job }) {
  const [updateJob] = useMutation(UPDATE_JOB);
  const { t } = useTranslation();
  const notification = useNotification();

  const onClick = async ({ key }) => {
    const result = await updateJob({
      variables: {
        jobId: job.id,
        job: { alt_transport: key === "null" ? null : key }
      }
    });

    if (!result.errors) {
      //  notification["success"]({ message: t("appointments.successes.saved") });
    } else {
      notification.error({
        title: t("jobs.errors.saving", {
          error: JSON.stringify(result.errors)
        })
      });
    }
  };

  const menu = {
    items: [
      ...(bodyshop.appt_alt_transport || []).map((alt) => ({
        key: alt,
        label: alt
      })),
      { key: "null", label: t("general.actions.clear") }
    ],
    onClick: onClick,
    defaultSelectedKeys: [job && job.alt_transport]
  };

  return (
    <Dropdown menu={menu}>
      <a href=" #" onClick={(e) => e.preventDefault()}>
        <DownOutlined />
      </a>
    </Dropdown>
  );
}

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