import { useEffect, useRef } from 'react';

import { DEFAULT_CURRENCY } from '@/app/(root)/account/constants';
import { AuraSubscriptionCard } from '@/components/card/AuraSubscriptionCard';
import { useEligibleDiscounts } from '@/hooks/useEligibleDiscounts';
import { CHECKOUT_SOURCE } from '@/lib/checkoutSource';
import {
  CtaButtons,
  PlanKey,
  SubscriptionInfo,
  UsagePlanDescription,
  UsagePlanSchema,
} from '@/state/sessionStore';
import { SubscriptionPeriod } from '@/utils/session';

interface ScrollablePlansProps {
  plans: UsagePlanSchema[];
  period: SubscriptionPeriod;
  currentSubscription: SubscriptionInfo | null;
  usagePlanDescriptions: Record<string, UsagePlanDescription>;
  ctaButtons?: CtaButtons | null;
  getPriceForPlan: (plan: UsagePlanSchema, period: string) => number;
  getFeatureDescriptions: (plan: UsagePlanSchema) => any[];
  handleSetPeriodAnnual: () => void;
}

export const ScrollablePlans = ({
  plans,
  period,
  currentSubscription,
  usagePlanDescriptions,
  ctaButtons,
  getPriceForPlan,
  getFeatureDescriptions,
  handleSetPeriodAnnual,
}: ScrollablePlansProps) => {
  const { Annual: ANNUAL } = SubscriptionPeriod;
  const containerRef = useRef<HTMLDivElement>(null);
  const { data: eligibleDiscountsResult } = useEligibleDiscounts();

  useEffect(() => {
    const proIndex = plans.findIndex((plan) => plan.plan_key === PlanKey.Pro);
    if (proIndex !== -1 && containerRef.current) {
      const container = containerRef.current;

      requestAnimationFrame(() => {
        const proCard = container.querySelector(
          `[data-plan-card]:nth-child(${proIndex + 1})`
        ) as HTMLElement;
        if (proCard) {
          const containerRect = container.getBoundingClientRect();
          const cardRect = proCard.getBoundingClientRect();
          const scrollLeft =
            proCard.offsetLeft - containerRect.width / 2 + cardRect.width / 2;

          container.scrollTo({
            left: Math.max(0, scrollLeft),
            behavior: 'smooth',
          });
        }
      });
    }
  }, [plans]);

  return (
    <div className='relative z-50'>
      <div
        ref={containerRef}
        className='scrollbar-hide flex snap-x snap-mandatory gap-6 overflow-x-auto pr-8 pl-8'
      >
        {plans?.map((plan: UsagePlanSchema) => (
          <div
            key={plan.id}
            data-plan-card
            className='w-[70vw] max-w-[70vw] min-w-[280px] flex-shrink-0 snap-center md:w-[70vw] md:max-w-[70vw]'
          >
            <AuraSubscriptionCard
              plan={plan}
              price={getPriceForPlan(plan, period)}
              priceBeforeDiscount={plan.monthly_price_usd}
              period={period}
              billed={period === ANNUAL ? 'yearly' : 'monthly'}
              features={getFeatureDescriptions(plan)}
              currentSubscription={currentSubscription}
              setPeriodAnnual={handleSetPeriodAnnual}
              planDescription={usagePlanDescriptions[plan.plan_key]}
              ctaButtons={ctaButtons}
              checkoutSource={CHECKOUT_SOURCE.SPLASH_PAGE}
              selectedCurrency={DEFAULT_CURRENCY}
              discountDetails={
                eligibleDiscountsResult?.eligible_discounts[plan.plan_key]?.[
                  period
                ]
              }
            />
          </div>
        ))}
      </div>
    </div>
  );
};
