'use client';

import { useStatsigClient } from '@statsig/react-bindings';
import { usePathname, useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import CreateFormContext from '@/app/(root)/create/v2/CreateFormContext';
import { useContextSelector } from '@/hooks/useContextSelector';
import { isProOrPremier } from '@/utils/session';
import { canUseModel } from '@/utils/utils';

export const useCrowModal = () => {
  const { session, genForm } = useStores();
  const statsigClient = useStatsigClient();
  const [showCrowModal, setShowCrowModal] = useState(false);
  const pathname = usePathname();
  const router = useRouter();
  const [canUseCrow, setCanUseCrow] = useState(false);
  const [_, setModelType] = useContextSelector(CreateFormContext, (context) =>
    context.selectState<string>(['global', 'model'])
  );

  useEffect(() => {
    // Check if we should show the crow modal
    setCanUseCrow(canUseModel(session.billingModels, 'chirp-crow'));
    const hasNotSeenCrowModal = !genForm.hasSeenCrowModal;
    const sessionLoaded = session.sessionIsLoaded;
    const subLoaded = session.isSubLoaded;
    const v5WebUiEnabled = statsigClient.checkGate('web-v5-promo');
    // Don't show modal on pages with COEP restrictions (cross-origin isolation)
    const isOnCOEPRestrictedRoute =
      pathname.startsWith('/edit') ||
      pathname.startsWith('/edit-v3') ||
      pathname.startsWith('/studio') ||
      pathname.startsWith('/edit-legacy');
    const notOnCOEPRestrictedRoute = !isOnCOEPRestrictedRoute;

    const shouldShow =
      hasNotSeenCrowModal &&
      sessionLoaded &&
      subLoaded &&
      v5WebUiEnabled &&
      notOnCOEPRestrictedRoute;

    if (shouldShow) {
      setShowCrowModal(true);
    }
  }, [
    session.billingModels,
    genForm.hasSeenCrowModal,
    session.sessionIsLoaded,
    session.isSubLoaded,
    session.flags,
    session,
    pathname,
  ]);

  const handleModalClose = () => {
    setShowCrowModal(false);
    genForm.hasSeenCrowModal = true;
  };

  const handleUpgrade = () => {
    if (canUseCrow) {
      // Pro/Premier users - take to create page
      setModelType('chirp-crow');
      if (pathname !== '/create') {
        router.push('/create');
      }
    } else {
      // Free users - take to pricing page
      window.location.href = '/pricing';
    }
    handleModalClose();
  };

  const getButtonText = () => {
    if (canUseCrow) {
      return 'Create with v5';
    } else {
      return 'Upgrade for access';
    }
  };

  const getDescription = () => {
    return "Superior sound, intuitive control, and\nstudio-quality results. It's the powerful\nfoundation for everything that's coming.";
  };

  return {
    showCrowModal,
    handleModalClose,
    handleUpgrade,
    buttonText: getButtonText(),
    description: getDescription(),
    isProOrPremier: isProOrPremier(session),
  };
};
