import { useApolloClient, useMutation } from "@apollo/client";
import { Menu, notification } from "antd";
import parsePhoneNumber from "libphonenumber-js";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import {
  GET_CURRENT_QUESTIONSET_ID,
  INSERT_CSI,
} from "../../graphql/csi.queries";
import { setEmailOptions } from "../../redux/email/email.actions";
import {
  openChatByPhone,
  setMessage,
} from "../../redux/messaging/messaging.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { DateTimeFormatter } from "../../utils/DateFormatter";
import { TemplateList } from "../../utils/TemplateConstants";
import { HasFeatureAccess } from "../feature-wrapper/feature-wrapper.component";

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

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

  const handleCreateCsi = async (e) => {
    logImEXEvent("job_create_csi");

    //Is tehre already a CSI?
    if (!job.csiinvites || job.csiinvites.length === 0) {
      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,
                },
              },
            },
          },
          refetchQueries: ["GET_JOB_BY_PK"],
          awaitRefetchQueries: true,
        });

        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({
            jobid: job.id,
            messageOptions: {
              to: [job.ownr_ea],
              replyTo: bodyshop.email,
            },
            template: {
              name: TemplateList("job_special").csi_invitation_action.key,
              variables: {
                id: result.data.insert_csi.returning[0].id,
              },
            },
          });

        if (e.key === "text") {
          const p = parsePhoneNumber(job.ownr_ph1, "CA");
          if (p && p.isValid()) {
            openChatByPhone({
              phone_num: p.formatInternational(),
              jobid: job.id,
            });
            setMessage(
              `${window.location.protocol}//${window.location.host}/csi/${result.data.insert_csi.returning[0].id}`
            );
          } else {
            notification["error"]({
              message: t("messaging.error.invalidphone"),
            });
          }
        }
        if (e.key === "generate") {
          //copy it to clipboard.
          navigator.clipboard.writeText(
            `${window.location.protocol}//${window.location.host}/csi/${result.data.insert_csi.returning[0].id}`
          );
        }
      } else {
        notification["error"]({
          message: t("csi.errors.notconfigured"),
        });
      }
    } else {
      if (e.key === "email")
        setEmailOptions({
          jobid: job.id,
          messageOptions: {
            to: [job.ownr_ea],
            replyTo: bodyshop.email,
          },
          template: {
            name: TemplateList("job_special").csi_invitation_action.key,
            variables: {
              id: job.csiinvites[0].id,
            },
          },
        });

      if (e.key === "text") {
        const p = parsePhoneNumber(job.ownr_ph1, "CA");
        if (p && p.isValid()) {
          openChatByPhone({
            phone_num: p.formatInternational(),
            jobid: job.id,
          });
          setMessage(
            `${window.location.protocol}//${window.location.host}/csi/${job.csiinvites[0].id}`
          );
        } else {
          notification["error"]({
            message: t("messaging.error.invalidphone"),
          });
        }
      }

      if (e.key === "generate") {
        //copy it to clipboard.
        navigator.clipboard.writeText(
          `${window.location.protocol}//${window.location.host}/csi/${job.csiinvites[0].id}`
        );
      }
    }
  };

  if (!HasFeatureAccess({ featureName: "csi", bodyshop })) return <></>;

  return (
    <Menu.SubMenu
      key="sendcsi"
      title={t("jobs.actions.sendcsi")}
      disabled={!job.converted}
      {...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.Item
        onClick={handleCreateCsi}
        key="generate"
        disabled={job.csiinvites && job.csiinvites.length > 0}
      >
        {t("jobs.actions.generatecsi")}
      </Menu.Item>
      <Menu.Divider />
      {job.csiinvites.map((item, idx) => {
        return item.completedon ? (
          <Menu.Item key={idx}>
            <Link to={`/manage/shop/csi?responseid=${item.id}`}>
              <DateTimeFormatter>{item.completedon}</DateTimeFormatter>
            </Link>
          </Menu.Item>
        ) : (
          <Menu.Item
            key={idx}
            onClick={() => {
              navigator.clipboard.writeText(
                `${window.location.protocol}//${window.location.host}/csi/${item.id}`
              );
            }}
          >
            {t("general.actions.copylink")}
          </Menu.Item>
        );
      })}
    </Menu.SubMenu>
  );
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(JobsDetailHeaderCsi);
