define(["jquery", "core/ajax"], ($, Ajax) => {
  let isGenerateAppDashboardUrlLoading = false;
  let quizSettingUpgradeInfoContainer;
  let quizSettingUpgradeCta;
  let quizSettingLoadingIconUpgradeCta;
  let quizSettingUpgradeFailedInfo;
  let quizSettingFreeLimitation;
  let cmid = null;
  let manageSubscriptionContainer;
  let manageSubscriptionFailedInfo;
  let manageSubscriptionLoadingIcon;

  const fetchAppData = () => {
    const wsfunction = "quizaccess_quilgo_fetch_app_data";
    let params = {};
    if (cmid != null) {
      params = { cmid: Number(cmid) };
    }
    const request = { methodname: wsfunction, args: params };

    return Ajax.call([request])[0];
  };

  const generateAppDashboardUrl = () => {
    const wsfunction = "quizaccess_quilgo_generate_app_dashboard_url";
    const request = { methodname: wsfunction, args: {} };

    return Ajax.call([request])[0];
  };

  const initFreeLimitationInfoElements = () => {
    quizSettingUpgradeInfoContainer = $(".upgrade-info-container");
    quizSettingUpgradeCta = $(".quilgo-upgrade-cta");
    quizSettingLoadingIconUpgradeCta = $(".upgrade-cta-loading-icon");
    quizSettingUpgradeFailedInfo = $(".upgrade-failed-info");
    quizSettingFreeLimitation = $(".free-limitation");

    quizSettingUpgradeCta.on("click", async () => {
      if (isGenerateAppDashboardUrlLoading === true) {
        return;
      }

      isGenerateAppDashboardUrlLoading = true;
      quizSettingLoadingIconUpgradeCta.removeClass("d-none");
      quizSettingUpgradeFailedInfo.addClass("d-none");

      try {
        const dashboardAppUrl = await generateAppDashboardUrl();
        if (dashboardAppUrl.dashboardUrl == null) {
          throw new Error("Dashboard url empty");
        }

        window.open(dashboardAppUrl.dashboardUrl, "_blank").focus();
      } catch (error) {
        quizSettingUpgradeFailedInfo.removeClass("d-none");
      } finally {
        isGenerateAppDashboardUrlLoading = false;
        quizSettingLoadingIconUpgradeCta.addClass("d-none");
      }
    });
  };

  const initManageSubscriptionElements = () => {
    manageSubscriptionContainer = $(".manage-subscription-container");
    manageSubscriptionLoadingIcon = $(".manage-subscription-loading-icon");
    manageSubscriptionFailedInfo = $(".manage-subscription-failed-info");

    manageSubscriptionContainer.on("click", async () => {
      if (isGenerateAppDashboardUrlLoading === true) {
        return;
      }

      isGenerateAppDashboardUrlLoading = true;
      manageSubscriptionLoadingIcon.removeClass("d-none");
      manageSubscriptionFailedInfo.addClass("d-none");

      try {
        const dashboardAppUrl = await generateAppDashboardUrl();
        if (dashboardAppUrl.dashboardUrl == null) {
          throw new Error("Dashboard url empty");
        }

        window.open(dashboardAppUrl.dashboardUrl, "_blank").focus();
      } catch (error) {
        manageSubscriptionFailedInfo.removeClass("d-none");
      } finally {
        isGenerateAppDashboardUrlLoading = false;
        manageSubscriptionLoadingIcon.addClass("d-none");
      }
    });
  };

  return {
    initQuizSettingInfo: async (_cmid) => {
      initFreeLimitationInfoElements();
      cmid = _cmid;
      const appDataResponse = await fetchAppData();
      const isPlanDataExists = appDataResponse.planData != null;
      const isFreePlan = appDataResponse.isFree;
      const isUpgradeInfoShown = isPlanDataExists && isFreePlan;

      if (isUpgradeInfoShown === false) {
        return;
      }

      quizSettingFreeLimitation.text(appDataResponse.concurrentSessionsLimit);
      quizSettingUpgradeInfoContainer.removeClass("d-none");
    },
    initManageSubscription: async () => {
      const appDataResponse = await fetchAppData();
      const isPlanDataExists = appDataResponse.planData != null;
      const isFreePlan = appDataResponse.isFree;
      const isUpgradeInfoShown = isPlanDataExists && isFreePlan;

      initFreeLimitationInfoElements();
      initManageSubscriptionElements();
      if (isUpgradeInfoShown) {
        quizSettingFreeLimitation.text(appDataResponse.concurrentSessionsLimit);
        quizSettingUpgradeInfoContainer.removeClass("d-none");
      }
    },
  };
});
