import { useEngagementMedium, useMutation, useParentValue, useProgramId, useQuery, useUserIdentity, } from "@saasquatch/component-boilerplate";
import { useState } from "@saasquatch/stencil-hooks";
import { useEffect } from "@saasquatch/universal-hooks";
import { gql } from "graphql-request";
import { REFERRAL_CODES_NAMESPACE, } from "../sqm-referral-codes/useReferralCodes";
const ShareLinkQuery = gql `
  query shareLink($programId: ID, $engagementMedium: UserEngagementMedium!) {
    user: viewer {
      ... on User {
        shareLink(
          programId: $programId
          engagementMedium: $engagementMedium
          shareMedium: DIRECT
        )
      }
    }
  }
`;
const WIDGET_ENGAGEMENT_EVENT = gql `
  mutation loadEvent($eventMeta: UserAnalyticsEvent!) {
    createUserAnalyticsEvent(eventMeta: $eventMeta)
  }
`;
export function useQRCode(props) {
  var _a;
  const programId = useProgramId();
  const user = useUserIdentity();
  const engagementMedium = useEngagementMedium();
  const contextData = useParentValue(REFERRAL_CODES_NAMESPACE);
  const [qrLink, setQrUrl] = useState(null);
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);
  const { data, errors, loading: requestLoading, } = useQuery(ShareLinkQuery, { programId, engagementMedium }, !(user === null || user === void 0 ? void 0 : user.jwt) || (contextData === null || contextData === void 0 ? void 0 : contextData.shareLink) !== undefined);
  const [sendLoadEvent] = useMutation(WIDGET_ENGAGEMENT_EVENT);
  const shareLink = (_a = data === null || data === void 0 ? void 0 : data.user) === null || _a === void 0 ? void 0 : _a.shareLink;
  const qrPrefix = `${shareLink}?qrCode`;
  const completeLoading = requestLoading || loading;
  useEffect(() => {
    if (!shareLink)
      return;
    const getQrCode = async () => {
      setQrUrl(`${shareLink}?qrCode&qrCodeImageFormat=svg&qrCodeQuietZoneSize=0`);
    };
    getQrCode();
  }, [shareLink]);
  const fireEvent = async () => {
    sendLoadEvent({
      eventMeta: {
        programId,
        id: user === null || user === void 0 ? void 0 : user.id,
        accountId: user === null || user === void 0 ? void 0 : user.accountId,
        type: "USER_REFERRAL_PROGRAM_ENGAGEMENT_EVENT",
        meta: {
          engagementMedium,
          shareMedium: "DIRECT",
        },
      },
    });
  };
  const createDownloadable = async () => {
    try {
      const res = await fetch(`${qrPrefix}&qrCodeSize=800&qrCodeImageFormat=png`);
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      // Successful
      if (blob)
        fireEvent();
      // Trigger download
      const link = document.createElement("a");
      link.href = url;
      link.download = "qrCode.png";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
    catch (e) {
      console.error("Failed to fetch QR code:", e);
      setError(true);
    }
  };
  const createPrintable = async () => {
    try {
      const res = await fetch(`${qrPrefix}&qrCodeSize=1000&qrCodeImageFormat=png&qrCodeErrorCorrectionLevel=H`);
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      // Successful
      if (blob)
        fireEvent();
      // Trigger print
      const page = window.open("about:blank", "_new");
      const img = page.document.createElement("img");
      img.src = url;
      img.onload = () => {
        page.print();
        page.close();
      };
      page.document.body.appendChild(img);
    }
    catch (e) {
      console.error("Failed to fetch QR code: ", e);
      setError(true);
    }
  };
  return {
    ...props,
    loading: completeLoading,
    qrLink,
    error: error,
    createDownloadable,
    createPrintable,
  };
}
