import { useStatsigClient } from '@statsig/react-bindings';
import { useEffect } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { ModalTypes } from '@/components/modal/constants/ModalTypes';
import { useModalContext } from '@/context/ModalContext';
import { FeatureKey, FeatureUpsellConfig } from '@/state/sessionStore';
import { UNDERLYING_PLAN_KEY, isSubscriber } from '@/utils/session';

/**
 * Launch the appropriate modal if the user is out of credits or currency
 */
export default function useUpsells() {
  const { session: sessionStore, menus: menusStore } = useStores();
  const { openModal } = useModalContext();

  const statsigClient = useStatsigClient();

  const canSetUpsellConfig =
    sessionStore.sessionIsLoaded &&
    sessionStore.isSubLoaded &&
    statsigClient?.client?.loadingStatus === 'Ready';

  const planKey = sessionStore.sub.plan
    ?.plan_key as keyof typeof UNDERLYING_PLAN_KEY;

  useEffect(() => {
    if (canSetUpsellConfig) {
      const config = statsigClient.getDynamicConfig('feature_upsell_configs');
      const configContent = config.value as unknown as FeatureUpsellConfig;
      menusStore.setFeatureUpsellConfig(configContent);
      const filteredConfigContent = Object.fromEntries(
        Object.entries(configContent).filter(([_, feature]) => {
          return !feature.required_plans.includes(UNDERLYING_PLAN_KEY[planKey]);
        })
      );
      menusStore.setFeatureUpsellConfig(filteredConfigContent);
    }
  }, [canSetUpsellConfig, planKey, statsigClient, menusStore]);

  const { notifyOutOfCredits, notifyOutOfConcurrency } = sessionStore;

  useEffect(() => {
    if (notifyOutOfCredits) {
      sessionStore.notifyOutOfCredits = false;
      // Non-free users get the "invite friend" modal when they are out of credits
      if (isSubscriber(sessionStore)) {
        openModal(ModalTypes.INVITE_FRIEND, 'OutOfCredits');
        return;
      }
      // Free users get v4-styled upgrade
      sessionStore.notifyOutOfCredits = false;
      menusStore.setCurrentUpsellFeature(FeatureKey.OUT_OF_CREDITS);
      openModal(ModalTypes.UPSELL_MODAL);
    }
  }, [notifyOutOfCredits, sessionStore, menusStore, openModal]);

  useEffect(() => {
    if (notifyOutOfConcurrency) {
      sessionStore.notifyOutOfConcurrency = false;
      menusStore.setCurrentUpsellFeature(FeatureKey.SIMULTANEOUS_GENS);
      openModal(ModalTypes.UPSELL_MODAL);
    }
  }, [notifyOutOfConcurrency, sessionStore, menusStore, openModal]);
}
