import { format, parseISO } from 'date-fns';
import React from 'react';

import {
  getDisplayPrice,
  getPriceForPlanAndCurrency,
} from '@/app/(root)/account/AuraSubscriptions/CurrencySelector';
import { ModalButton } from '@/app/(root)/account/AuraSubscriptions/modals/shared/ModalButton';
import {
  PriceDivider,
  PriceRow,
  PricingSection,
  TaxDisplay,
} from '@/app/(root)/account/AuraSubscriptions/modals/shared/PriceDisplay';
import { Currency } from '@/app/(root)/account/constants';
import { ButtonVariant } from '@/components/button/Button';
import SpinnerSVG from '@/components/svg/SpinnerSVG';
import { useBillingTaxInfo } from '@/hooks/useBillingTax';
import { PlanChangePreview, UsagePlanSchema } from '@/state/sessionStore';
import { SubscriptionPeriod } from '@/utils/session';
import { calculateTaxAmount, isTaxApplicable } from '@/utils/tax';

const getDisplayPriceForPlan = ({
  plan,
  period,
  currency,
}: {
  plan: UsagePlanSchema;
  period: SubscriptionPeriod;
  currency: Currency;
}): string => {
  if (!plan) return '';
  const price = getPriceForPlanAndCurrency(plan, currency, period);
  return getDisplayPrice(price, currency);
};

interface Props {
  applyImmediately: boolean;
  isLoading: boolean;
  actionName: string;
  preview: PlanChangePreview | null;
  currentPlan?: UsagePlanSchema | null;
  targetPlan: UsagePlanSchema;
  period: SubscriptionPeriod;
  currentSubscriptionPeriod: SubscriptionPeriod;
  currency: Currency;
  onBack: () => void;
  onConfirm: () => void;
}

const ConfirmStep: React.FC<Props> = ({
  applyImmediately,
  isLoading,
  actionName,
  preview,
  currentPlan,
  targetPlan,
  period,
  currentSubscriptionPeriod,
  currency,
  onBack,
  onConfirm,
}) => {
  const displayCurrency = (preview?.proration.currency as Currency) || currency;
  const { data: taxInfo } = useBillingTaxInfo();
  const hasTax = isTaxApplicable(taxInfo);

  const calculateTaxForPlan = (
    plan: UsagePlanSchema,
    period: SubscriptionPeriod
  ) => {
    const planPrice =
      getPriceForPlanAndCurrency(plan, displayCurrency, period) || 0;
    return calculateTaxAmount(taxInfo, planPrice);
  };

  // Determine the button label based on loading state and action type
  const buttonLabel = (() => {
    if (isLoading) {
      if (applyImmediately) return 'Purchasing...';
      switch (actionName) {
        case 'Upgrade':
          return 'Upgrading...';
        case 'Downgrade':
          return 'Downgrading...';
        default:
          return 'Changing...';
      }
    }

    // Not loading
    return applyImmediately ? 'Purchase' : `Confirm ${actionName}`;
  })();

  return (
    <div>
      {applyImmediately ? (
        <div className='flex flex-col'>
          <p className='mb-4 text-white/80'>
            Your saved payment method will be charged instantly upon
            confirmation.
          </p>

          <PricingSection>
            <PriceRow
              label={targetPlan.name}
              amount={preview?.proration.price || 0}
              currency={displayCurrency}
              isBold
            />

            <PriceRow
              label='Discount: Unused Monthly Credits'
              amount={preview?.proration.discount || 0}
              currency={displayCurrency}
              isNegative
            />

            {hasTax && (
              <>
                <PriceDivider />
                <PriceRow
                  label='Subtotal'
                  amount={preview?.proration.subtotal || 0}
                  currency={displayCurrency}
                  isBold
                />
                <TaxDisplay
                  taxAmount={calculateTaxAmount(
                    taxInfo,
                    preview?.proration.subtotal || 0
                  )}
                  currency={displayCurrency}
                />
              </>
            )}

            <PriceDivider />
            <PriceRow
              label='Total'
              amount={
                (preview?.proration.subtotal || 0) +
                calculateTaxAmount(taxInfo, preview?.proration.subtotal || 0)
              }
              currency={displayCurrency}
              isBold
            />
          </PricingSection>
        </div>
      ) : (
        currentPlan && (
          <div className='flex flex-col'>
            <p className='mb-4 text-white/80'>
              At the end of your current billing cycle on{' '}
              {preview?.period_end
                ? format(parseISO(preview.period_end), 'MMM d, y')
                : null}
              , your subscription plan will automatically renew and update to
              your newly chosen plan.
            </p>

            <PricingSection>
              <div className='mb-2 flex justify-between'>
                <span>From {currentPlan.name}</span>
                <span>
                  {getDisplayPriceForPlan({
                    plan: currentPlan,
                    period: currentSubscriptionPeriod,
                    currency: displayCurrency,
                  })}{' '}
                  / {currentSubscriptionPeriod}
                </span>
              </div>

              <div className='mb-2 flex justify-between font-bold'>
                <span>To {targetPlan.name}</span>
                <span>
                  {getDisplayPriceForPlan({
                    plan: targetPlan,
                    period,
                    currency: displayCurrency,
                  })}{' '}
                  / {period}
                </span>
              </div>

              {hasTax && (
                <>
                  <PriceDivider />
                  <PriceRow
                    label='Subtotal'
                    amount={
                      getPriceForPlanAndCurrency(
                        targetPlan,
                        displayCurrency,
                        period
                      ) || 0
                    }
                    currency={displayCurrency}
                  />
                  <TaxDisplay
                    taxAmount={calculateTaxForPlan(targetPlan, period)}
                    currency={displayCurrency}
                  />
                </>
              )}

              <PriceDivider />
              <PriceRow
                label={`Amount due on ${preview?.period_end ? format(parseISO(preview.period_end), 'MMM d, y') : ''}`}
                amount={
                  (getPriceForPlanAndCurrency(
                    targetPlan,
                    displayCurrency,
                    period
                  ) || 0) + calculateTaxForPlan(targetPlan, period)
                }
                currency={displayCurrency}
                isBold
              />
            </PricingSection>
          </div>
        )
      )}

      <div className='flex justify-center gap-3'>
        <ModalButton variant={ButtonVariant.LightGlass} onClick={onBack}>
          Back
        </ModalButton>
        <ModalButton
          variant={ButtonVariant.Primary}
          onClick={onConfirm}
          disabled={isLoading}
          icon={isLoading ? <SpinnerSVG className='fill-black' /> : null}
        >
          {buttonLabel}
        </ModalButton>
      </div>
    </div>
  );
};

export default ConfirmStep;
