import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { ArrowRight } from 'lucide-react';
import { SubscriptionPricingCards } from './SubscriptionPricingCards';
import { PricingComparisonModal } from './PricingComparisonModal';
import { subscriptionService } from '../../api';
import type { PlanMetadata, SubscriptionTier } from '../../api';
import { getRegisterUrl } from '../../utils/navigation';

export const PricingSection: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [showComparisonModal, setShowComparisonModal] = useState(false);
  const [plans, setPlans] = useState<Record<SubscriptionTier, PlanMetadata> | null>(null);
  const [billingCycle, setBillingCycle] = useState<'monthly' | 'yearly'>('monthly');

  useEffect(() => {
    loadPlans();
  }, []);

  const loadPlans = async () => {
    try {
      const availablePlans = await subscriptionService.fetchAvailablePlans();
      setPlans(availablePlans.plans);
    } catch (err) {
      console.error('Failed to load plans for comparison:', err);
    }
  };

  const handlePlanSelect = (tier: string) => {
    // Use the updated getRegisterUrl function that supports billing cycle
    navigate(getRegisterUrl(tier, billingCycle));
  };

  return (
    <div>
      {/* Billing Cycle Toggle */}
      <div className="flex justify-center mb-8">
        <div className="inline-flex rounded-lg border-2 border-[var(--border-primary)] p-1 bg-[var(--bg-secondary)]">
          <button
            onClick={() => setBillingCycle('monthly')}
            className={`px-6 py-2 rounded-md text-sm font-semibold transition-all ${
              billingCycle === 'monthly'
                ? 'bg-[var(--color-primary)] text-white shadow-md'
                : 'text-[var(--text-secondary)] hover:bg-[var(--bg-primary)] hover:text-[var(--text-primary)]'
            }`}
          >
            {t('billing.monthly', 'Mensual')}
          </button>
          <button
            onClick={() => setBillingCycle('yearly')}
            className={`px-6 py-2 rounded-md text-sm font-semibold transition-all flex items-center gap-2 ${
              billingCycle === 'yearly'
                ? 'bg-[var(--color-primary)] text-white shadow-md'
                : 'text-[var(--text-secondary)] hover:bg-[var(--bg-primary)] hover:text-[var(--text-primary)]'
            }`}
          >
            {t('billing.yearly', 'Anual')}
            <span className="text-xs font-bold text-green-600 dark:text-green-400">
              {t('billing.save_percent', 'Ahorra 17%')}
            </span>
          </button>
        </div>
      </div>

      {/* Pricing Cards */}
      <SubscriptionPricingCards
        mode="landing"
        showPilotBanner={true}
        pilotTrialMonths={3}
        showComparison={false}
        billingCycle={billingCycle} // Pass selected billing cycle
      />

      {/* Feature Comparison Link */}
      <div className="text-center mt-12">
        <button
          onClick={() => setShowComparisonModal(true)}
          className="text-[var(--color-primary)] hover:text-white font-semibold inline-flex items-center gap-2 px-4 py-2 rounded-lg transition-all duration-200 hover:bg-[var(--color-primary)]"
        >
          {t('landing:pricing.compare_link', 'Ver comparación completa de características')}
          <ArrowRight className="w-4 h-4" />
        </button>
      </div>

      {/* Comparison Modal */}
      {plans && (
        <PricingComparisonModal
          isOpen={showComparisonModal}
          onClose={() => setShowComparisonModal(false)}
          plans={plans}
          onSelectPlan={handlePlanSelect}
        />
      )}
    </div>
  );
};
