import { AppRouterInstance } from 'next/dist/shared/lib/app-router-context.shared-runtime';

import { ApiClient } from '@/lib/apiClient';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { Clip, ClipsStore } from '@/state/clipStore';
import { MenusStore } from '@/state/menusStore';
import { SessionStore } from '@/state/sessionStore';
import {
  DOWNLOAD_UPGRADE_EXPERIMENT_NAME,
  GenerationPriotityLevel,
} from '@/utils/constants';
import { checkDownloadQuota } from '@/utils/downloadQuota';
import { isProOrPremier } from '@/utils/session';

export interface ModalRenderer {
  renderRemixModal: (onDownloadAnyway: () => void) => void;
  renderUpgradeModal: (
    onDownload: () => void,
    onUpgrade: () => void,
    onClose: () => void
  ) => void;
}

/**
 * Consolidated download gating logic shared between songMenuConfig.tsx and ClipMenuItems.tsx
 * Handles complex permission checking for downloads including:
 * - User ownership checks
 * - Download quota validation
 * - Commercial rights for remix content
 * - Pro/Premier vs Free user flows
 */
export const processDownloadGating = async (
  clip: Clip,
  menus: MenusStore,
  session: SessionStore,
  clips: ClipsStore,
  router: AppRouterInstance,
  statsigClient: any,
  apiClient: ApiClient,
  confirmFn: () => void,
  modalRenderer: ModalRenderer
): Promise<void> => {
  // Check if downloads gating is enabled via experiment
  const experiment = statsigClient.getExperiment('download_gating');
  const isDownloadGatingEnabled = experiment.get(
    'enable-download-gating',
    false
  );

  // First, always check ownership regardless of subscription tier
  if (isDownloadGatingEnabled) {
    try {
      const quotaCheck = await checkDownloadQuota(apiClient, clip.id);

      // If user owns this clip, bypass all quota restrictions and proceed with download
      if (quotaCheck.clipOwnedByUser) {
        confirmFn();
        return;
      }

      const eligibilityResult = await apiClient.GET(
        '/api/clips/{clip_id}/commercial_rights_eligible/',
        {
          params: { path: { clip_id: clip.id } },
        }
      );
      const isRemixOfNonOwned = !eligibilityResult.data?.eligible;

      // For remix tracks (of non-owned content), handle differently
      if (isRemixOfNonOwned) {
        if (isProOrPremier(session)) {
          confirmFn();
          return;
        }

        menus.openCommercialRightsModal(clip.id, confirmFn);
        return;
      }

      if (isProOrPremier(session) && clip.user_id === session.userId) {
        menus.openCommercialRightsModal(clip.id, confirmFn);
        return;
      }

      if (!isProOrPremier(session)) {
        menus.openCommercialRightsModal(
          clip.id,
          quotaCheck.canDownload ? confirmFn : () => {}
        );
        return;
      }
    } catch (error) {
      // Failed to check download quota, allow download to proceed
    }
  }

  if (
    clip.metadata?.is_remix &&
    !!clips.parentClipByClipId?.[clip?.id]?.user_handle &&
    clips.parentClipByClipId?.[clip?.id]?.user_handle !== session.user?.handle
  ) {
    modalRenderer.renderRemixModal(confirmFn);
  } else if (
    session.experiments?.[DOWNLOAD_UPGRADE_EXPERIMENT_NAME] &&
    clip.metadata?.priority !== GenerationPriotityLevel.Pro &&
    !session.roles?.['pro'] &&
    !session.flags?.['skip-paywall']
  ) {
    const onDownload = () => {
      confirmFn();
      logWebUserEvent({
        actionName: 'MakeDownloadUpgradeModalSelection',
        context: {
          selection: 'download',
        },
      });
    };

    const onUpgrade = () => {
      router.push('/account');
      logWebUserEvent({
        actionName: 'MakeDownloadUpgradeModalSelection',
        context: {
          selection: 'upgrade',
        },
      });
    };

    const onClose = () => {
      logWebUserEvent({
        actionName: 'DismissDownloadUpgradeModal',
        context: {},
      });
    };

    modalRenderer.renderUpgradeModal(onDownload, onUpgrade, onClose);
  } else {
    confirmFn();
  }
};
