'use client';

/* eslint jsx-a11y/no-static-element-interactions: warn */
import { observer } from 'mobx-react-lite';
import { useRouter } from 'next/navigation';
import React, { useEffect } from 'react';
import { createPortal } from 'react-dom';

import { getMonthlyPriceForPlanAndCurrency } from '@/app/(root)/account/AuraSubscriptions/CurrencySelector';
import { ButtonVariant } from '@/components/button/Button';
import CloseButton from '@/components/button/CloseButton';
import logWebUserEvent from '@/logging/logWebUserEvent';
import {
  FeatureKey,
  FeatureUpsellConfig,
  PlanKey,
  UsagePlanSchema,
} from '@/state/sessionStore';

import { FeaturesAndPlansCarousel } from './FeaturesAndPlansCarousel';

interface UpsellCardModalProps {
  isOpen: boolean;
  onClose: () => void;
  features: FeatureUpsellConfig;
  currentUpsellFeature: FeatureKey;
  currentSubscription: any;
  usagePlanDescriptions: Record<string, any>;
  plans: UsagePlanSchema[];
}

const UpsellCardModal: React.FC<UpsellCardModalProps> = observer(
  ({
    isOpen,
    onClose,
    features,
    currentUpsellFeature,
    currentSubscription,
    usagePlanDescriptions,
    plans,
  }) => {
    const router = useRouter();
    const transparentSvg = 'https://cdn-o.suno.com/transparent.svg';
    const modalRef = React.useRef<HTMLDivElement>(null);

    const currentPlan = currentSubscription?.plan;
    const hasHighestPlan = currentPlan?.plan_key === PlanKey.Premier;

    useEffect(() => {
      if (isOpen) {
        logWebUserEvent({
          actionName: 'UpsellModalViewed',
          componentContext: currentUpsellFeature,
        });
      }
    }, [isOpen, currentUpsellFeature]);

    const handleOverlayClick = (
      e: React.MouseEvent<HTMLDivElement, MouseEvent>
    ) => {
      if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
        onClose();
      }
    };

    if (!isOpen) {
      return null;
    }

    // Don't show upsell modal if user already has Premier (highest plan)
    if (hasHighestPlan) {
      return null;
    }

    // Modal content copied from AuraModal, but rendered inline here
    return typeof window !== 'undefined'
      ? createPortal(
          <div
            className='modal-overlay fixed inset-0 z-[100000] flex items-center justify-center bg-black/60'
            onMouseDown={handleOverlayClick}
          >
            <div
              ref={modalRef}
              className='scrollbar-hide pointer-events-auto relative max-h-[calc(100svh-9rem)] w-full max-w-[calc(100vw-2rem)] overflow-y-auto rounded-[32px] border border-white/15 bg-black/60 sm:max-h-[90vh] sm:max-w-[400px]'
              style={{ background: 'none' }}
            >
              <div className='absolute top-0 left-0 h-full w-full overflow-hidden rounded-[32px]'>
                <img
                  src={transparentSvg}
                  alt=''
                  className='h-full w-full object-cover'
                />
                <div
                  className='absolute inset-0 h-full'
                  style={{
                    background:
                      'linear-gradient(rgba(14, 8, 8, 0) -69.77%, #0E0808 53.4%)',
                  }}
                />
              </div>
              <div className='scrollbar-hide pointer-events-auto relative z-10 max-h-[calc(100svh-9rem)] w-full max-w-[calc(100vw-2rem)] overflow-y-auto rounded-[32px] px-6 pt-0 pb-6 text-left text-white sm:max-h-[90vh] sm:max-w-[400px]'>
                <CloseButton
                  variant={ButtonVariant.Tertiary}
                  onClick={onClose}
                  className='absolute top-2 right-2 z-10'
                />
                <FeaturesAndPlansCarousel
                  features={features}
                  plans={plans}
                  initialFeatureKey={currentUpsellFeature}
                  usagePlanDescriptions={usagePlanDescriptions}
                  getMonthlyPriceForPlanAndCurrency={
                    getMonthlyPriceForPlanAndCurrency
                  }
                  currentSubscription={currentSubscription}
                  currentUpsellFeature={currentUpsellFeature}
                />
                <div className='mb-[-20] text-center'>
                  <button
                    onClick={() => {
                      logWebUserEvent({
                        actionName: 'SeeAllPlansClicked',
                        componentContext: currentUpsellFeature,
                      });
                      onClose();
                      router.push('/account');
                    }}
                    className='mb-5 text-foreground-tertiary transition-colors hover:text-foreground-primary'
                  >
                    See all plans →
                  </button>
                </div>
              </div>
            </div>
          </div>,
          document.body
        )
      : null;
  }
);

export default UpsellCardModal;
