'use client';

import { observer } from 'mobx-react-lite';
import { useSearchParams } from 'next/navigation';
import { useEffect, useMemo, useRef, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { Currency, DEFAULT_CURRENCY } from '@/app/(root)/account/constants';
import { validateCurrency } from '@/app/(root)/account/utils';
import Button, { ButtonShape, ButtonVariant } from '@/components/button/Button';
import AuraModal from '@/components/modal/AuraModal';
import SpinnerSVG from '@/components/svg/SpinnerSVG';
import TitleText from '@/components/title/TitleText';
import { useCurrencyOptions } from '@/hooks/useCurrencyOptions';
import { useEligibleDiscounts } from '@/hooks/useEligibleDiscounts';
import usePageViewLog from '@/hooks/usePageViewLog';
import {
  useDefaultCurrency,
  useUsagePlanDescriptionsResponse,
} from '@/hooks/usePricing';
import useSubscriptionInfo from '@/hooks/useSubscriptionInfo';
import { ArrowDownIcon } from '@/icons';
import { CHECKOUT_SOURCE } from '@/lib/checkoutSource';
import logWebUserEvent from '@/logging/logWebUserEvent';
import {
  getCurrencyFromUrlParams,
  getUserCurrencyPreference,
  setUserCurrencyPreference,
} from '@/utils/currencyStorage';
import { ModalStep } from '@/utils/subscriptionModalUtils';

import { ComparePlansTable } from './ComparePlansTable';
import { CurrencySelector } from './CurrencySelector';
import { CurrentSubscription } from './CurrentSubscription';
import { FAQ } from './FAQ';
import { HarvardBanner, shouldShowHarvardBanner } from './HarvardBanner';
import { MobileBillingWarning } from './MobileBillingWarning';
import { PastDueWarning } from './PastDueWarning';
import { Plans } from './Plans';
import CancelSubscriptionModalContent from './modals/CancelSubscriptionModalContent';

const cancelModalTitleMap: Record<ModalStep, string> = {
  [ModalStep.Select]: 'Cancel Plan',
  [ModalStep.Confirm]: 'Cancel Plan',
  [ModalStep.CouponConfirm]: 'Are you sure?',
  [ModalStep.Scheduled]: 'Cancellation Scheduled',
  [ModalStep.Error]: 'Error',
  [ModalStep.Completing]: 'Processing...',
  [ModalStep.Success]: 'Success',
  [ModalStep.Offer]: 'Before you go...',
  [ModalStep.ConfirmOffer]: 'Confirm update',
  [ModalStep.SurveyOther]: 'Tell us more',
  [ModalStep.CancelSurvey]: 'Before you go...',
};

export const AuraSubscriptionsBase = observer(() => {
  const { session } = useStores();
  const searchParams = useSearchParams();
  const comparePlansRef = useRef<HTMLDivElement>(null);
  const faqsRef = useRef<HTMLDivElement>(null);
  const currentSubscriptionRef = useRef<HTMLDivElement>(null);
  const [selectedCurrency, setSelectedCurrency] =
    useState<Currency>(DEFAULT_CURRENCY);
  const [isCancelModalOpen, setIsCancelModalOpen] = useState(false);
  const [cancelModalStep, setCancelModalStep] = useState<ModalStep>(
    ModalStep.Confirm
  );

  // Fetch usage plan descriptions (CTA buttons and plan descriptions)
  const { data: descriptionsResponse } = useUsagePlanDescriptionsResponse();

  // Fetch eligible discounts for discount message banner
  const {
    data: eligibleDiscountsResult,
    isLoading: isEligibleDiscountsLoading,
  } = useEligibleDiscounts();

  // Get available currencies based on feature flag
  const availableCurrencies = useCurrencyOptions();
  const availableCurrencyValues = useMemo(
    () => availableCurrencies.map((c) => c.value),
    [availableCurrencies]
  );

  // Get location-based default currency
  const { data: locationBasedCurrency } = useDefaultCurrency();

  // Enhanced currency selection with priority order:
  // 1. Plan currency from session (highest priority - existing customer billing currency)
  // 2. URL parameter (high priority - marketing/direct links)
  // 3. User's stored preference (medium priority - user choice)
  // 4. Location-based currency from API (low priority - user location)
  // 5. DEFAULT_CURRENCY (fallback)
  // All currencies are validated against available currencies from feature flag
  useEffect(() => {
    // Don't set currency until session is loaded to avoid premature decisions
    if (!session.isSubLoaded) {
      return;
    }

    // Check plan currency first (highest priority for existing customers)
    if (session.sub?.plan_currency) {
      const planCurrency = session.sub.plan_currency.toUpperCase();
      // Check if the plan currency is a valid Currency enum value
      if (Object.values(Currency).includes(planCurrency as Currency)) {
        setSelectedCurrency(
          validateCurrency(planCurrency as Currency, availableCurrencyValues)
        );
        return;
      }
    }

    let newCurrency: Currency = DEFAULT_CURRENCY;

    // Check URL parameter (high priority for marketing/direct links)
    const urlCurrency = getCurrencyFromUrlParams(searchParams);
    if (urlCurrency) {
      newCurrency = urlCurrency;
    } else {
      // Check user's stored preference (medium priority for user choice)
      const storedCurrency = getUserCurrencyPreference();
      if (storedCurrency !== DEFAULT_CURRENCY) {
        newCurrency = storedCurrency;
      } else if (locationBasedCurrency) {
        // Use location-based currency if no stored preference (low priority)
        const apiCurrency = locationBasedCurrency.toUpperCase();
        if (Object.values(Currency).includes(apiCurrency as Currency)) {
          newCurrency = apiCurrency as Currency;
        }
      }
    }

    setSelectedCurrency(validateCurrency(newCurrency, availableCurrencyValues));
  }, [
    searchParams,
    session.isSubLoaded,
    session.sub?.plan_currency,
    locationBasedCurrency,
    availableCurrencyValues,
  ]);

  const scrollToComparePlans = () => {
    comparePlansRef.current?.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
    });
  };

  const scrollToFaqs = () => {
    faqsRef.current?.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
    });
  };

  const query = useSubscriptionInfo();

  usePageViewLog({
    actionName: 'PageViewed',
    componentContext: 'subscription',
  });
  const currentSubscription = query.data;
  const isMobileSubscription = ['apple', 'google'].includes(
    currentSubscription?.subscription_platform?.toLowerCase() || ''
  );

  // Get current plan level for highlighting in the comparison chart
  const currentPlanKey = currentSubscription?.plan?.plan_key || null;

  // Get available plans from the API
  const availablePlans = currentSubscription?.plans || [];

  return (
    <div className='relative flex min-h-screen w-full flex-col items-center overflow-y-auto bg-background-primary'>
      <div className='absolute top-0 left-0 h-full w-full'>
        <img
          src='https://cdn-o.suno.com/auras-v2/Aura-1.png'
          className='h-full w-full object-cover'
          alt=''
        />
        <div
          className='absolute inset-0'
          style={{
            background:
              'linear-gradient(var(--color-background-fog-thick) -69.77%, var(--color-background-primary) 53.4%)',
          }}
        />
      </div>

      {/* CurrentSubscription outside the max-width container */}
      {currentSubscription?.is_active && (
        <div ref={currentSubscriptionRef} className='relative z-10 w-full p-6'>
          <CurrentSubscription
            sub={currentSubscription}
            isMobileSubscription={isMobileSubscription}
            onCancelSubscription={() => {
              setIsCancelModalOpen(true);
            }}
            showCancelButton={
              !!session.user &&
              !!currentSubscription?.is_active &&
              currentSubscription?.plan?.plan_key !== 'basic'
            }
          />
        </div>
      )}

      <div className='relative z-10 mb-[120px] flex w-full max-w-[1280px] flex-col items-start gap-6 p-6'>
        {!currentSubscription ? (
          <div className='w-full text-center'>
            <SpinnerSVG />
          </div>
        ) : (
          <>
            {isMobileSubscription && (
              <MobileBillingWarning
                subscriptionPlatform={
                  currentSubscription?.subscription_platform ?? undefined
                }
              />
            )}
            {currentSubscription?.is_past_due && <PastDueWarning />}
            {!isEligibleDiscountsLoading &&
              shouldShowHarvardBanner(eligibleDiscountsResult) && (
                <HarvardBanner />
              )}
            {session.isMultiCurrencyStripeEnabled &&
              !currentSubscription?.is_active && (
                <div className='flex w-full justify-end'>
                  <CurrencySelector
                    value={selectedCurrency}
                    onChange={(currency) => {
                      const validatedCurrency = validateCurrency(
                        currency,
                        availableCurrencyValues
                      );
                      setSelectedCurrency(validatedCurrency);
                      setUserCurrencyPreference(validatedCurrency);
                    }}
                    supportedCurrencies={availableCurrencyValues}
                  />
                </div>
              )}
            <div className='flex flex-col gap-[100px]'>
              <div className='mt-6 flex w-full flex-col gap-10'>
                <div className='flex flex-col items-center'>
                  <TitleText
                    text='Manage your Suno plan'
                    className='leading-[48px] text-foreground-primary/90'
                  />
                  <span className='font-sans text-sm text-foreground-secondary'>
                    Select the plan that best fits your needs
                  </span>
                  <Plans
                    plans={availablePlans}
                    currentSubscription={currentSubscription}
                    usagePlanDescriptions={
                      descriptionsResponse?.usage_plan_descriptions || {}
                    }
                    ctaButtons={descriptionsResponse?.cta_buttons ?? null}
                    selectedCurrency={selectedCurrency}
                    checkoutSource={CHECKOUT_SOURCE.ACCOUNT_PAGE}
                  />
                </div>
                <div className='flex flex-col items-center gap-8'>
                  <div className='flex flex-row flex-wrap gap-2'>
                    <Button
                      variant={ButtonVariant.Secondary}
                      shape={ButtonShape.Pill}
                      onClick={scrollToFaqs}
                    >
                      FAQs <ArrowDownIcon />
                    </Button>
                    <Button
                      className='whitespace-nowrap'
                      variant={ButtonVariant.Secondary}
                      shape={ButtonShape.Pill}
                      onClick={scrollToComparePlans}
                    >
                      Compare plans <ArrowDownIcon />
                    </Button>
                  </div>
                  <div className='flex flex-col items-center gap-2'>
                    <h2 className='font-sans text-xs font-bold'>Need More?</h2>

                    <span className='w-full text-center font-sans text-xs text-foreground-secondary'>
                      Credits included in subscriptions do not carry over from
                      day to day or month to month. Purchased top up credits do
                      not expire, but require an active subscription to use. See
                      the{' '}
                      <a
                        className='underline'
                        href='https://suno.com/legal/terms'
                      >
                        terms of service
                      </a>{' '}
                      for limitations on commercial use. Email us at{' '}
                      <a className='underline' href='mailto:billing@suno.com'>
                        billing@suno.com
                      </a>{' '}
                      with any questions.
                    </span>
                  </div>
                </div>
              </div>

              <FAQ ref={faqsRef} items={session.usagePlanFaqs} />

              <ComparePlansTable
                ref={comparePlansRef}
                tableComparison={session.usagePlanTableComparison}
                currentPlanKey={currentPlanKey}
                plans={availablePlans}
                usagePlanDescriptions={
                  descriptionsResponse?.usage_plan_descriptions || {}
                }
              />
            </div>
          </>
        )}
      </div>

      {/* Cancel Subscription Modal */}
      {currentSubscription?.is_active && (
        <AuraModal
          open={isCancelModalOpen}
          onOpenChange={(open) => {
            setIsCancelModalOpen(open);
            if (!open) {
              setCancelModalStep(ModalStep.Confirm);
            } else {
              logWebUserEvent({
                actionName: 'SubCancelFlowFeaturesAboutToLoseStepShown',
                context: {
                  currentPeriod: currentSubscription?.period || '',
                  currentUsagePlanId: currentSubscription?.plan?.id || '',
                  modalStep: 1,
                },
              });
            }
          }}
          title={cancelModalTitleMap[cancelModalStep]}
        >
          <CancelSubscriptionModalContent
            currentSubscription={currentSubscription}
            onClose={() => {
              setIsCancelModalOpen(false);
              setCancelModalStep(ModalStep.Confirm);
            }}
            step={cancelModalStep}
            onStepChange={setCancelModalStep}
            isOpen={isCancelModalOpen}
          />
        </AuraModal>
      )}
    </div>
  );
});
