/**
 * Subscription Step Component
 * Second step of registration - plan selection and billing cycle
 * Updated to use professional SubscriptionPricingCards component
 */

import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '../../ui';
import { SubscriptionPricingCards } from '../../subscription/SubscriptionPricingCards';
import { subscriptionService } from '../../../api';

interface SubscriptionStepProps {
  selectedPlan: 'starter' | 'professional' | 'enterprise';
  billingCycle: 'monthly' | 'yearly';
  useTrial: boolean;
  couponCode?: string;
  updateField: (field: string, value: any) => void;
  onNext: () => void;
  onBack: () => void;
  isPilot: boolean;
}

export const SubscriptionStep: React.FC<SubscriptionStepProps> = ({
  selectedPlan,
  billingCycle,
  useTrial,
  couponCode,
  updateField,
  onNext,
  onBack,
  isPilot
}) => {
  const { t } = useTranslation();
  const [loadingPlanMetadata, setLoadingPlanMetadata] = useState(false);
  const [lastFetchedPlan, setLastFetchedPlan] = useState<string | null>(null);
  
  // Fetch plan metadata when selectedPlan changes, with proper guards to prevent infinite loops
  useEffect(() => {
    let isMounted = true;
    
    const fetchPlanMetadata = async () => {
      // Only fetch if we have a selected plan and it's different from the last fetched plan
      if (selectedPlan && selectedPlan !== lastFetchedPlan && isMounted) {
        setLoadingPlanMetadata(true);
        try {
          const metadata = await subscriptionService.getPlanMetadata(selectedPlan);
          if (metadata && isMounted) {
            updateField('planMetadata', {
              monthly_price: metadata.monthly_price,
              yearly_price: metadata.yearly_price,
              name: metadata.name,
              description: metadata.description
            });
            // Update the last fetched plan to prevent duplicate calls
            setLastFetchedPlan(selectedPlan);
          }
        } catch (error) {
          console.error('Failed to fetch plan metadata:', error);
          // Update with fallback metadata if API call fails
          if (isMounted) {
            const fallbackMetadata = getFallbackPlanMetadata(selectedPlan);
            updateField('planMetadata', fallbackMetadata);
            setLastFetchedPlan(selectedPlan); // Still update to prevent retry
          }
        } finally {
          if (isMounted) {
            setLoadingPlanMetadata(false);
          }
        }
      }
    };
    
    fetchPlanMetadata();
    
    // Automatically enable trial and apply PILOT2025 coupon for pilot users
    if (isPilot) {
      if (!useTrial) {
        updateField('useTrial', true);
      }
      if (!couponCode) {
        updateField('couponCode', 'PILOT2025');
      }
    }
    
    return () => {
      isMounted = false;
    };
  }, [selectedPlan, updateField, lastFetchedPlan, isPilot, useTrial, couponCode]);

  const getFallbackPlanMetadata = (planId: string) => {
    // Fallback metadata that matches backend defaults
    const fallbackData = {
      starter: {
        monthly_price: 9.99,
        yearly_price: 99.99,
        name: t('auth:plan_starter', 'Starter'),
        description: t('auth:plan_starter_desc', 'Basic plan for small businesses')
      },
      professional: {
        monthly_price: 29.99,
        yearly_price: 299.99,
        name: t('auth:plan_professional', 'Professional'),
        description: t('auth:plan_professional_desc', 'Advanced plan for growing businesses')
      },
      enterprise: {
        monthly_price: 99.99,
        yearly_price: 999.99,
        name: t('auth:plan_enterprise', 'Enterprise'),
        description: t('auth:plan_enterprise_desc', 'Complete solution for large businesses')
      }
    };
    
    return fallbackData[planId as keyof typeof fallbackData] || {
      monthly_price: 0,
      yearly_price: 0,
      name: planId,
      description: ''
    };
  };
  
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onNext();
  };
  
  return (
    <div className="subscription-step">
      <h2 className="text-2xl font-bold mb-6">
        {t('auth:register.choose_plan', 'Choose Your Plan')}
      </h2>
      
      {/* Professional Pricing Cards Component */}
      <SubscriptionPricingCards
        mode="selection"
        selectedPlan={selectedPlan}
        onPlanSelect={(planKey) => updateField('planId', planKey)}
        showPilotBanner={isPilot}
        pilotCouponCode={isPilot ? 'PILOT2025' : undefined}
        pilotTrialMonths={isPilot ? 3 : 0}
        billingCycle={billingCycle}
        onBillingCycleChange={(cycle) => updateField('billingInterval', cycle)}
        className="mb-8"
      />
      
      {/* Navigation */}
      <div className="flex justify-between mt-8">
        <Button type="button" variant="secondary" size="lg" onClick={onBack}>
          {t('auth:register.back', 'Back')}
        </Button>
        <Button type="submit" variant="primary" size="lg" onClick={handleSubmit}>
          {t('auth:register.continue', 'Continue')}
        </Button>
      </div>
    </div>
  );
};

export default SubscriptionStep;