'use client';

import { useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';

import {
  Currency,
  SUBSCRIPTION_PAGE_VERSIONS,
} from '@/app/(root)/account/constants';
import { useApiClient } from '@/lib/apiClient';
import logWebUserEvent from '@/logging/logWebUserEvent';
import {
  PlanChangePreview,
  SubscriptionInfo,
  UsagePlanSchema,
} from '@/state/sessionStore';
import { SubscriptionPeriod } from '@/utils/session';
import {
  SubscriptionAction,
  canUpgradeImmediately,
} from '@/utils/subscriptionActions';
import { ModalStep } from '@/utils/subscriptionModalUtils';

import {
  useChangePlan,
  useChangePreview,
  usePurchaseStatusPolling,
} from './shared/hooks';
import ConfirmStep from './steps/shared/ConfirmStep';
import ErrorStep from './steps/shared/ErrorStep';
import SuccessStep from './steps/shared/SuccessStep';

interface Props {
  currentSubscription: SubscriptionInfo;
  targetPlan: UsagePlanSchema;
  period: SubscriptionPeriod;
  onClose: () => void;
  selectedCurrency: Currency;
  action?: SubscriptionAction;
}

const actionName = 'Change';

const ChangeCommitmentModalContent: React.FC<Props> = ({
  currentSubscription,
  targetPlan,
  period,
  onClose,
  selectedCurrency,
  action,
}) => {
  const apiClient = useApiClient();
  const queryClient = useQueryClient();

  const [preview, setPreview] = useState<PlanChangePreview | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [step, setStep] = useState<ModalStep>(ModalStep.Confirm);
  const [purchaseId, setPurchaseId] = useState<string | null>(null);
  const [purchaseStatus, setPurchaseStatus] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const isChangingFromMonthlyToYearly =
    currentSubscription?.period === SubscriptionPeriod.Monthly &&
    period === SubscriptionPeriod.Annual;

  // Force delayed application if action is changeCommitmentDelayedOnly
  const forceDelayed =
    action === SubscriptionAction.ChangeCommitmentDelayedOnly;
  const applyImmediately =
    isChangingFromMonthlyToYearly &&
    !forceDelayed &&
    canUpgradeImmediately(currentSubscription);

  const changePreviewMutation = useChangePreview(apiClient, {
    onSuccess: (data) => setPreview(data),
  });

  useEffect(() => {
    changePreviewMutation.mutate({
      plan_key: targetPlan.plan_key,
      period,
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Handle purchase status polling
  usePurchaseStatusPolling(
    apiClient,
    purchaseId,
    purchaseStatus,
    (newStatus) => {
      setPurchaseStatus(newStatus);
      setIsLoading(false);
      setStep(ModalStep.Scheduled);
    }
  );

  const changePlanMutation = useChangePlan(apiClient, {
    onMutate: () => setIsLoading(true),
    onSuccess: async (data) => {
      if (data?.ok === false) {
        queryClient.invalidateQueries({ queryKey: ['subscriptionInfo'] });
        setIsLoading(false);
        setErrorMessage(data?.error || null);
        setStep(ModalStep.Error);
        return;
      } else if (!data?.id) {
        // Immediate plan change - no payment processing needed
        queryClient.invalidateQueries({ queryKey: ['subscriptionInfo'] });
        setIsLoading(false);
        setStep(ModalStep.Scheduled);
      } else {
        // Payment processing required - set up polling
        setPurchaseId(data.id);
      }
    },
  });

  if (step === ModalStep.Scheduled) {
    return (
      <SuccessStep
        actionName={actionName}
        applyImmediately={applyImmediately}
        onClose={onClose}
      />
    );
  }

  if (step === ModalStep.Error) {
    return (
      <ErrorStep
        actionName='Plan Change'
        onClose={onClose}
        errorMessage={errorMessage}
      />
    );
  }

  return (
    <ConfirmStep
      applyImmediately={applyImmediately}
      isLoading={isLoading}
      actionName={actionName}
      preview={preview}
      currentPlan={currentSubscription?.plan}
      targetPlan={targetPlan}
      period={period}
      currentSubscriptionPeriod={
        currentSubscription.period as SubscriptionPeriod
      }
      currency={selectedCurrency}
      onBack={onClose}
      onConfirm={() => {
        logWebUserEvent({
          actionName: 'ChangePlanConfirmButtonClicked',
          context: {
            usagePlanId: targetPlan?.id,
            period: period,
            immediate: applyImmediately,
            subPageVersion: SUBSCRIPTION_PAGE_VERSIONS.aura,
            buttonText: actionName,
            currentUsagePlanId: currentSubscription?.plan?.id || '',
            currentPeriod: currentSubscription?.period || '',
          },
        });
        changePlanMutation.mutate({
          plan_key: targetPlan.plan_key,
          period,
          immediate: applyImmediately,
        });
      }}
    />
  );
};

export default ChangeCommitmentModalContent;
