import { useEngagementMedium, useUserIdentity, useQuery, useParentValue, useMutation, } from "@saasquatch/component-boilerplate";
import { gql } from "graphql-request";
import { useProgramId, getEnvironmentSDK, } from "@saasquatch/component-boilerplate";
import { REFERRAL_CODES_NAMESPACE, SET_CODE_COPIED, } from "../sqm-referral-codes/useReferralCodes";
const MessageLinkQuery = gql `
  query (
    $programId: ID
    $engagementMedium: UserEngagementMedium!
    $shareMedium: ReferralShareMedium!
  ) {
    viewer {
      ... on User {
        messageLink(
          programId: $programId
          engagementMedium: $engagementMedium
          shareMedium: $shareMedium
        )
        shareLink(programId: $programId, engagementMedium: $engagementMedium)
      }
    }
  }
`;
function NativeShare(props, directLink, undefinedErrorText, unsupportedPlatformText) {
  const title = props.sharetitle || "Share title";
  const text = props.sharetext || "Share text";
  if (directLink === "undefined") {
    return alert(undefinedErrorText);
  }
  if (window.navigator.share) {
    window.navigator
      .share({
      title,
      text,
      url: directLink,
    })
      .catch((error) => console.error("Error on web share", error));
  }
  else {
    alert(unsupportedPlatformText);
  }
}
function FacebookShare(directLink, messageLink, errorText) {
  if (messageLink === "undefined" || directLink === "undefined") {
    return alert(errorText);
  }
  if (typeof SquatchAndroid.shareOnFacebook !== "undefined") {
    return SquatchAndroid.shareOnFacebook(directLink, messageLink);
  }
  else {
    return GenericShare(messageLink, errorText);
  }
}
function GenericShare(messageLink, errorText) {
  return messageLink ? (window.location.href = messageLink) : alert(errorText);
}
export function useShareButton(props) {
  var _a, _b, _c, _d;
  const { sharetitle, sharetext, medium } = props;
  const programId = props.programId ? props.programId : useProgramId();
  const user = useUserIdentity();
  const engagementMedium = useEngagementMedium();
  const variables = {
    engagementMedium,
    programId: programId,
    shareMedium: medium.toUpperCase(),
  };
  const contextData = useParentValue(REFERRAL_CODES_NAMESPACE);
  const overrideData = contextData === null || contextData === void 0 ? void 0 : contextData[medium];
  // only queries if a programId is available
  const res = useQuery(MessageLinkQuery, variables, !(user === null || user === void 0 ? void 0 : user.jwt) || !programId || overrideData !== undefined);
  const [setCopied, copiedRes] = useMutation(SET_CODE_COPIED);
  const directLink = (overrideData === null || overrideData === void 0 ? void 0 : overrideData.shareLink) || ((_b = (_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.shareLink);
  const environment = getEnvironmentSDK();
  const hide = (medium.toLocaleUpperCase() === "SMS" &&
    window.orientation === undefined) ||
    (medium.toLocaleUpperCase() === "DIRECT" && !window.navigator.share);
  const messageLink = (overrideData === null || overrideData === void 0 ? void 0 : overrideData.messageLink) || ((_d = (_c = res.data) === null || _c === void 0 ? void 0 : _c.viewer) === null || _d === void 0 ? void 0 : _d.messageLink);
  async function onClick() {
    if (overrideData) {
      await setCopied({ referralCode: contextData.referralCode });
      contextData.refresh();
    }
    if (medium.toLocaleUpperCase() === "FACEBOOK" &&
      environment.type === "SquatchAndroid") {
      FacebookShare(directLink, messageLink, props.errorText);
    }
    else if (medium.toLocaleUpperCase() === "DIRECT") {
      NativeShare({ sharetitle, sharetext }, directLink, props.errorText, props.unsupportedPlatformText);
    }
  }
  const isPlainLink = !(medium.toLocaleUpperCase() === "FACEBOOK" &&
    environment.type === "SquatchAndroid") &&
    medium.toLocaleUpperCase() !== "DIRECT" &&
    messageLink;
  const userAgent = window.navigator.userAgent.toLowerCase(), safari = /safari/.test(userAgent), ios = /iphone|ipod|ipad/.test(userAgent);
  const openInSameTab = ios && !safari;
  return {
    ...props,
    loading: res.loading && !(overrideData === null || overrideData === void 0 ? void 0 : overrideData.messageLink),
    messageLink,
    isPlainLink,
    onClick,
    openInSameTab,
    hide,
  };
}
