import { useMutation, useApolloClient } from "@apollo/react-hooks";
import { Menu, notification } from "antd";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
  INSERT_CSI,
  GET_CURRENT_QUESTIONSET_ID,
} from "../../graphql/csi.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { setEmailOptions } from "../../redux/email/email.actions";
import { TemplateList } from "../../utils/TemplateConstants";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser'
  bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({
  setEmailOptions: (e) => dispatch(setEmailOptions(e)),
});

export function JobsDetailHeaderCsi({
  setEmailOptions,
  bodyshop,
  job,
  ...props
}) {
  const { t } = useTranslation();
  const [insertCsi] = useMutation(INSERT_CSI);
  const client = useApolloClient();

  const handleCreateCsi = async (e) => {
    console.log("e.target.key", e.key);

    const questionSetResult = await client.query({
      query: GET_CURRENT_QUESTIONSET_ID,
    });

    if (questionSetResult.data.csiquestions.length > 0) {
      const result = await insertCsi({
        variables: {
          csiInput: {
            jobid: job.id,
            bodyshopid: bodyshop.id,
            questionset: questionSetResult.data.csiquestions[0].id,
            relateddata: {
              job: {
                id: job.id,
                ownr_fn: job.ownr_fn,
                ro_number: job.ro_number,
                v_model_yr: job.v_model_yr,
                v_make_desc: job.v_make_desc,
                v_model_desc: job.v_model_desc,
              },
              bodyshop: {
                city: bodyshop.city,
                email: bodyshop.email,
                state: bodyshop.state,
                country: bodyshop.country,
                address1: bodyshop.address1,
                address2: bodyshop.address2,
                shopname: bodyshop.shopname,
                zip_post: bodyshop.zip_post,
                logo_img_path: bodyshop.logo_img_path,
              },
            },
          },
        },
      });

      if (!!!result.errors) {
        notification["success"]({ message: t("csi.successes.created") });
      } else {
        notification["error"]({
          message: t("csi.errors.creating", {
            message: JSON.stringify(result.errors),
          }),
        });
        return;
      }
      if (e.key === "email")
        setEmailOptions({
          messageOptions: {
            to: job.ownr_ea,
            replyTo: bodyshop.email,
          },
          template: {
            name: TemplateList.csi_invitation.key,
            variables: {
              id: result.data.insert_csi.returning[0].id,
            },
          },
        });

      if (e.key === "text") console.log("TODO Handling texting"); //TODO Implement texting.
    } else {
      notification["error"]({
        message: t("csi.errors.notconfigured"),
      });
    }
  };

  return (
    <Menu.SubMenu title={t("jobs.actions.sendcsi")} {...props}>
      <Menu.Item
        onClick={handleCreateCsi}
        key='email'
        disabled={!!!job.ownr_ea}>
        {t("general.labels.email")}
      </Menu.Item>
      <Menu.Item
        onClick={handleCreateCsi}
        key='text'
        disabled={!!!job.ownr_ph1}>
        {t("general.labels.text")}
      </Menu.Item>
    </Menu.SubMenu>
  );
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(JobsDetailHeaderCsi);
