import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { Check, Star, ArrowRight, Package, TrendingUp, Settings, Loader, Users, MapPin, CheckCircle, Zap, ChevronDown, ChevronUp } from 'lucide-react';
import { Button, Card, Badge } from '../ui';
import {
  subscriptionService,
  type PlanMetadata,
  type SubscriptionTier,
  SUBSCRIPTION_TIERS
} from '../../api';
import { getRegisterUrl } from '../../utils/navigation';
import { ValuePropositionBadge } from './ValuePropositionBadge';
import { PricingFeatureCategory } from './PricingFeatureCategory';

type BillingCycle = 'monthly' | 'yearly';
type DisplayMode = 'landing' | 'selection';

interface SubscriptionPricingCardsProps {
  mode?: DisplayMode;
  selectedPlan?: string;
  onPlanSelect?: (planKey: string) => void;
  showPilotBanner?: boolean;
  pilotCouponCode?: string;
  pilotTrialMonths?: number;
  className?: string;
}

export const SubscriptionPricingCards: React.FC<SubscriptionPricingCardsProps> = ({
  mode = 'landing',
  selectedPlan,
  onPlanSelect,
  showPilotBanner = false,
  pilotCouponCode,
  pilotTrialMonths = 3,
  className = ''
}) => {
  const { t } = useTranslation('subscription');
  const [plans, setPlans] = useState<Record<SubscriptionTier, PlanMetadata> | null>(null);
  const [billingCycle, setBillingCycle] = useState<BillingCycle>('monthly');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [expandedPlan, setExpandedPlan] = useState<string | null>(null);

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

  const loadPlans = async () => {
    try {
      setLoading(true);
      setError(null);
      const availablePlans = await subscriptionService.fetchAvailablePlans();
      setPlans(availablePlans.plans);
    } catch (err) {
      console.error('Failed to load plans:', err);
      setError('No se pudieron cargar los planes. Por favor, intenta nuevamente.');
    } finally {
      setLoading(false);
    }
  };

  const getPrice = (plan: PlanMetadata) => {
    return billingCycle === 'monthly' ? plan.monthly_price : plan.yearly_price;
  };

  const getSavings = (plan: PlanMetadata) => {
    if (billingCycle === 'yearly') {
      return subscriptionService.calculateYearlySavings(
        plan.monthly_price,
        plan.yearly_price
      );
    }
    return null;
  };

  const getPlanIcon = (tier: SubscriptionTier) => {
    switch (tier) {
      case SUBSCRIPTION_TIERS.STARTER:
        return <Package className="w-6 h-6" />;
      case SUBSCRIPTION_TIERS.PROFESSIONAL:
        return <TrendingUp className="w-6 h-6" />;
      case SUBSCRIPTION_TIERS.ENTERPRISE:
        return <Settings className="w-6 h-6" />;
      default:
        return <Package className="w-6 h-6" />;
    }
  };

  const formatFeatureName = (feature: string): string => {
    const featureNames: Record<string, string> = {
      'inventory_management': 'Gestión de inventario',
      'sales_tracking': 'Seguimiento de ventas',
      'basic_recipes': 'Recetas básicas',
      'production_planning': 'Planificación de producción',
      'basic_reporting': 'Informes básicos',
      'mobile_app_access': 'Acceso desde app móvil',
      'email_support': 'Soporte por email',
      'easy_step_by_step_onboarding': 'Onboarding guiado paso a paso',
      'basic_forecasting': 'Pronósticos básicos',
      'demand_prediction': 'Predicción de demanda IA',
      'waste_tracking': 'Seguimiento de desperdicios',
      'order_management': 'Gestión de pedidos',
      'customer_management': 'Gestión de clientes',
      'supplier_management': 'Gestión de proveedores',
      'batch_tracking': 'Trazabilidad de lotes',
      'expiry_alerts': 'Alertas de caducidad',
      'advanced_analytics': 'Analíticas avanzadas',
      'custom_reports': 'Informes personalizados',
      'sales_analytics': 'Análisis de ventas',
      'supplier_performance': 'Rendimiento de proveedores',
      'waste_analysis': 'Análisis de desperdicios',
      'profitability_analysis': 'Análisis de rentabilidad',
      'weather_data_integration': 'Integración datos meteorológicos',
      'traffic_data_integration': 'Integración datos de tráfico',
      'multi_location_support': 'Soporte multi-ubicación',
      'location_comparison': 'Comparación entre ubicaciones',
      'inventory_transfer': 'Transferencias de inventario',
      'batch_scaling': 'Escalado de lotes',
      'recipe_feasibility_check': 'Verificación de factibilidad',
      'seasonal_patterns': 'Patrones estacionales',
      'longer_forecast_horizon': 'Horizonte de pronóstico extendido',
      'pos_integration': 'Integración POS',
      'accounting_export': 'Exportación contable',
      'basic_api_access': 'Acceso API básico',
      'priority_email_support': 'Soporte prioritario por email',
      'phone_support': 'Soporte telefónico',
      'scenario_modeling': 'Modelado de escenarios',
      'what_if_analysis': 'Análisis what-if',
      'risk_assessment': 'Evaluación de riesgos',
      'full_api_access': 'Acceso completo API',
      'unlimited_webhooks': 'Webhooks ilimitados',
      'erp_integration': 'Integración ERP',
      'custom_integrations': 'Integraciones personalizadas',
      'sso_saml': 'SSO/SAML',
      'advanced_permissions': 'Permisos avanzados',
      'audit_logs_export': 'Exportación de logs de auditoría',
      'compliance_reports': 'Informes de cumplimiento',
      'dedicated_account_manager': 'Gestor de cuenta dedicado',
      'priority_support': 'Soporte prioritario',
      'support_24_7': 'Soporte 24/7',
      'custom_training': 'Formación personalizada'
    };

    return featureNames[feature] || feature.replace(/_/g, ' ');
  };

  const handlePlanAction = (tier: string, plan: PlanMetadata) => {
    if (mode === 'selection' && onPlanSelect) {
      onPlanSelect(tier);
    }
  };

  if (loading) {
    return (
      <div className={`flex justify-center items-center py-20 ${className}`}>
        <Loader className="w-8 h-8 animate-spin text-[var(--color-primary)]" />
        <span className="ml-3 text-[var(--text-secondary)]">Cargando planes...</span>
      </div>
    );
  }

  if (error || !plans) {
    return (
      <div className={`text-center py-20 ${className}`}>
        <p className="text-[var(--color-error)] mb-4">{error}</p>
        <Button onClick={loadPlans}>Reintentar</Button>
      </div>
    );
  }

  return (
    <div className={className}>
      {/* Pilot Program Banner */}
      {showPilotBanner && pilotCouponCode && mode === 'selection' && (
        <Card className="p-6 mb-6 bg-gradient-to-r from-amber-50 via-orange-50 to-amber-50 dark:from-amber-900/20 dark:via-orange-900/20 dark:to-amber-900/20 border-2 border-amber-400 dark:border-amber-500">
          <div className="flex items-center gap-4">
            <div className="flex-shrink-0">
              <div className="w-14 h-14 bg-gradient-to-br from-amber-500 to-orange-500 rounded-full flex items-center justify-center shadow-lg">
                <Star className="w-7 h-7 text-white fill-white" />
              </div>
            </div>
            <div className="flex-1">
              <h3 className="text-xl font-bold text-amber-900 dark:text-amber-100 mb-1">
                Programa Piloto Activo
              </h3>
              <p className="text-sm text-amber-800 dark:text-amber-200">
                Como participante del programa piloto, obtienes <strong>{pilotTrialMonths} meses completamente gratis</strong> en el plan que elijas,
                más un <strong>20% de descuento de por vida</strong> si decides continuar.
              </p>
            </div>
          </div>
        </Card>
      )}

      {/* Billing Cycle Toggle */}
      <div className="flex justify-center mb-12">
        <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>

      {/* Plans Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {Object.entries(plans).map(([tier, plan]) => {
          const price = getPrice(plan);
          const savings = getSavings(plan);
          const isPopular = plan.popular;
          const tierKey = tier as SubscriptionTier;
          const isSelected = mode === 'selection' && selectedPlan === tier;

          const CardWrapper = mode === 'landing' ? Link : 'div';
          const cardProps = mode === 'landing'
            ? { to: plan.contact_sales ? '/contact' : getRegisterUrl(tier) }
            : { onClick: () => handlePlanAction(tier, plan) };

          return (
            <CardWrapper
              key={tier}
              {...cardProps}
              className={`
                group relative rounded-3xl p-8 transition-all duration-300 block no-underline
                ${mode === 'selection' ? 'cursor-pointer' : mode === 'landing' ? 'cursor-pointer' : ''}
                ${isSelected
                  ? 'border-2 border-[var(--color-primary)] bg-gradient-to-br from-[var(--color-primary)]/10 via-[var(--color-primary)]/5 to-transparent shadow-2xl ring-4 ring-[var(--color-primary)]/30 scale-[1.02]'
                  : isPopular
                    ? 'bg-gradient-to-br from-blue-700 via-blue-800 to-blue-900 shadow-2xl transform scale-105 z-10 ring-4 ring-[var(--color-primary)]/20 hover:scale-110 hover:ring-[var(--color-primary)]/40 hover:shadow-3xl'
                    : 'bg-[var(--bg-secondary)] border-2 border-[var(--border-primary)] hover:border-[var(--color-primary)] hover:shadow-2xl hover:scale-105 hover:ring-4 hover:ring-[var(--color-primary)]/20 hover:-translate-y-2'
                }
              `}
            >
              {/* Popular Badge */}
              {isPopular && (
                <div className="absolute -top-4 left-1/2 transform -translate-x-1/2">
                  <div className="bg-gradient-to-r from-[var(--color-secondary)] to-[var(--color-secondary-dark)] text-white px-6 py-2 rounded-full text-sm font-bold shadow-lg flex items-center gap-1">
                    <Star className="w-4 h-4 fill-current" />
                    Más Popular
                  </div>
                </div>
              )}

              {/* Icon */}
              <div className="absolute top-6 right-6">
                <div className={`w-12 h-12 rounded-full flex items-center justify-center ${
                  isPopular
                    ? 'bg-white/10 text-white'
                    : isSelected
                    ? 'bg-[var(--color-primary)]/20 text-[var(--color-primary)]'
                    : 'bg-[var(--color-primary)]/10 text-[var(--color-primary)]'
                }`}>
                  {getPlanIcon(tierKey)}
                </div>
              </div>

              {/* Header */}
              <div className={`mb-6 ${isPopular ? 'pt-4' : ''}`}>
                <h3 className={`text-2xl font-bold ${isPopular ? 'text-white' : isSelected ? 'text-[var(--color-primary)]' : 'text-[var(--text-primary)]'}`}>
                  {plan.name}
                </h3>
                <p className={`mt-3 text-sm leading-relaxed ${isPopular ? 'text-white' : 'text-[var(--text-secondary)]'}`}>
                  {plan.tagline_key ? t(plan.tagline_key) : plan.tagline || ''}
                </p>
              </div>

              {/* Pricing */}
              <div className="mb-6">
                <div className="flex items-baseline">
                  <span className={`text-5xl font-bold ${isPopular ? 'text-white' : isSelected ? 'text-[var(--color-primary)]' : 'text-[var(--text-primary)]'}`}>
                    {subscriptionService.formatPrice(price)}
                  </span>
                  <span className={`ml-2 text-lg ${isPopular ? 'text-white/95' : 'text-[var(--text-secondary)]'}`}>
                    /{billingCycle === 'monthly' ? 'mes' : 'año'}
                  </span>
                </div>

                {/* Savings Badge */}
                {savings && (
                  <div className={`mt-2 px-3 py-1 text-sm font-medium rounded-full inline-block ${
                    isPopular ? 'bg-white/20 text-white' : 'bg-green-500/10 text-green-600 dark:text-green-400'
                  }`}>
                    Ahorra {subscriptionService.formatPrice(savings.savingsAmount)}/año
                  </div>
                )}

                {/* Trial Badge */}
                {!savings && showPilotBanner && (
                  <div className={`mt-2 px-3 py-1 text-sm font-medium rounded-full inline-block ${
                    isPopular ? 'bg-white/20 text-white' : 'bg-[var(--color-success)]/10 text-[var(--color-success)]'
                  }`}>
                    {t('billing.free_months', { count: pilotTrialMonths })}
                  </div>
                )}
                {!savings && !showPilotBanner && (
                  <div className={`mt-2 px-3 py-1 text-sm font-medium rounded-full inline-block ${
                    isPopular ? 'bg-white/20 text-white' : 'bg-[var(--color-success)]/10 text-[var(--color-success)]'
                  }`}>
                    {t('billing.free_trial_days', { count: plan.trial_days })}
                  </div>
                )}
              </div>

              {/* ROI Badge */}
              {plan.roi_badge && !isPopular && (
                <div className="mb-4">
                  <ValuePropositionBadge roiBadge={plan.roi_badge} />
                </div>
              )}
              {plan.roi_badge && isPopular && (
                <div className="mb-4 bg-white/20 border border-white/30 rounded-lg px-4 py-3">
                  <p className="text-sm font-semibold text-white leading-tight flex items-center gap-2">
                    <svg className="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    {plan.roi_badge.translation_key ? t(plan.roi_badge.translation_key) : (plan.roi_badge.text_es || plan.roi_badge.text || '')}
                  </p>
                </div>
              )}

              {/* Good For / Recommended For */}
              {plan.recommended_for_key && (
                <div className={`mb-6 text-center px-4 py-2 rounded-lg ${
                  isPopular
                    ? 'bg-white/10 border border-white/20'
                    : 'bg-[var(--bg-secondary)] border border-[var(--border-primary)]'
                }`}>
                  <p className={`text-xs font-medium ${isPopular ? 'text-white/95' : 'text-[var(--text-secondary)]'}`}>
                    {t(plan.recommended_for_key)}
                  </p>
                </div>
              )}

              {/* Key Limits */}
              <div className={`mb-6 p-3 rounded-lg ${
                isPopular ? 'bg-white/15 border border-white/20' : isSelected ? 'bg-[var(--color-primary)]/5' : 'bg-[var(--bg-primary)]'
              }`}>
                <div className="space-y-2">
                  <div className="flex items-center justify-between text-xs">
                    <span className={isPopular ? 'text-white/95' : 'text-[var(--text-secondary)]'}>
                      <Users className="w-3 h-3 inline mr-1" />
                      {t('limits.users', 'Usuarios')}
                    </span>
                    <span className={`font-bold ${isPopular ? 'text-white' : isSelected ? 'text-[var(--color-primary)]' : 'text-[var(--text-primary)]'}`}>
                      {plan.limits.users || t('limits.unlimited', 'Ilimitado')}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-xs">
                    <span className={isPopular ? 'text-white/95' : 'text-[var(--text-secondary)]'}>
                      <MapPin className="w-3 h-3 inline mr-1" />
                      {t('limits.locations', 'Ubicaciones')}
                    </span>
                    <span className={`font-bold ${isPopular ? 'text-white' : isSelected ? 'text-[var(--color-primary)]' : 'text-[var(--text-primary)]'}`}>
                      {plan.limits.locations || t('limits.unlimited', 'Ilimitado')}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-xs">
                    <span className={isPopular ? 'text-white/95' : 'text-[var(--text-secondary)]'}>
                      <Package className="w-3 h-3 inline mr-1" />
                      {t('limits.products', 'Productos')}
                    </span>
                    <span className={`font-bold ${isPopular ? 'text-white' : isSelected ? 'text-[var(--color-primary)]' : 'text-[var(--text-primary)]'}`}>
                      {plan.limits.products || t('limits.unlimited', 'Ilimitado')}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-xs">
                    <span className={isPopular ? 'text-white/95' : 'text-[var(--text-secondary)]'}>
                      <TrendingUp className="w-3 h-3 inline mr-1" />
                      {t('limits.forecast', 'Pronóstico')}
                    </span>
                    <span className={`font-bold ${isPopular ? 'text-white' : isSelected ? 'text-[var(--color-primary)]' : 'text-[var(--text-primary)]'}`}>
                      {plan.limits.forecast_horizon_days ? `${plan.limits.forecast_horizon_days}d` : t('limits.unlimited', 'Ilimitado')}
                    </span>
                  </div>
                </div>
              </div>

              {/* Hero Features List */}
              <div className={`space-y-3 mb-6`}>
                {(plan.hero_features || plan.features.slice(0, 4)).map((feature) => (
                  <div key={feature} className="flex items-start">
                    <div className="flex-shrink-0 mt-1">
                      <div className={`w-5 h-5 rounded-full flex items-center justify-center ${
                        isPopular
                          ? 'bg-white'
                          : 'bg-[var(--color-success)]'
                      }`}>
                        <Check className={`w-3 h-3 ${isPopular ? 'text-[var(--color-primary)]' : 'text-white'}`} />
                      </div>
                    </div>
                    <span className={`ml-3 text-sm font-medium ${isPopular ? 'text-white' : 'text-[var(--text-primary)]'}`}>
                      {formatFeatureName(feature)}
                    </span>
                  </div>
                ))}
              </div>

              {/* Expandable Features - Show All Button */}
              {plan.features.length > 4 && (
                <div className="mb-8">
                  <button
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      setExpandedPlan(expandedPlan === tier ? null : tier);
                    }}
                    className={`w-full py-2 px-4 rounded-lg text-sm font-medium transition-all flex items-center justify-center gap-2 ${
                      isPopular
                        ? 'bg-white/10 hover:bg-white/20 text-white border border-white/20'
                        : 'bg-[var(--bg-secondary)] hover:bg-[var(--bg-primary)] text-[var(--text-secondary)] border border-[var(--border-primary)]'
                    }`}
                  >
                    {expandedPlan === tier ? (
                      <>
                        <ChevronUp className="w-4 h-4" />
                        Mostrar menos características
                      </>
                    ) : (
                      <>
                        <ChevronDown className="w-4 h-4" />
                        Ver todas las {plan.features.length} características
                      </>
                    )}
                  </button>

                  {/* Expanded Features List */}
                  {expandedPlan === tier && (
                    <div className={`mt-4 p-4 rounded-lg max-h-96 overflow-y-auto ${
                      isPopular
                        ? 'bg-white/10 border border-white/20'
                        : 'bg-[var(--bg-primary)] border border-[var(--border-primary)]'
                    }`}>
                      <div className="space-y-2">
                        {plan.features.map((feature) => (
                          <div key={feature} className="flex items-start py-1">
                            <Check className={`w-4 h-4 flex-shrink-0 mt-0.5 ${isPopular ? 'text-white' : 'text-[var(--color-success)]'}`} />
                            <span className={`ml-2 text-xs ${isPopular ? 'text-white/95' : 'text-[var(--text-primary)]'}`}>
                              {formatFeatureName(feature)}
                            </span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* Support */}
              <div className={`mb-6 text-sm text-center border-t pt-4 ${
                isPopular ? 'text-white/95 border-white/30' : 'text-[var(--text-secondary)] border-[var(--border-primary)]'
              }`}>
                {plan.support_key ? t(plan.support_key) : plan.support || ''}
              </div>

              {/* CTA Button */}
              {mode === 'landing' ? (
                <Button
                  className={`w-full py-4 text-base font-semibold transition-all duration-200 ${
                    isPopular
                      ? 'bg-white text-[var(--color-primary)] hover:bg-gray-100 shadow-lg hover:shadow-xl'
                      : 'border-2 border-[var(--color-primary)] text-[var(--color-primary)] hover:bg-[var(--color-primary)] hover:text-white'
                  }`}
                  variant={isPopular ? 'primary' : 'outline'}
                >
                  {plan.contact_sales ? 'Contactar Ventas' : 'Comenzar Prueba Gratuita'}
                </Button>
              ) : (
                <Button
                  className={`w-full py-4 text-base font-semibold transition-all duration-200 ${
                    isSelected
                      ? 'bg-[var(--color-primary)] text-white hover:bg-[var(--color-primary-dark)]'
                      : isPopular
                      ? 'bg-white text-[var(--color-primary)] hover:bg-gray-100'
                      : 'border-2 border-[var(--color-primary)] text-[var(--color-primary)] hover:bg-[var(--color-primary)] hover:text-white'
                  }`}
                  variant={isSelected || isPopular ? 'primary' : 'outline'}
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    handlePlanAction(tier, plan);
                  }}
                >
                  {isSelected ? (
                    <>
                      <CheckCircle className="mr-2 w-4 h-4" />
                      Seleccionado
                    </>
                  ) : (
                    <>
                      Elegir Plan
                      <ArrowRight className="ml-2 w-4 h-4" />
                    </>
                  )}
                </Button>
              )}

              <p className={`text-xs text-center mt-3 ${isPopular ? 'text-white/90' : 'text-[var(--text-secondary)]'}`}>
                {t('billing.free_months', { count: 3 })} • {t('billing.card_required')}
              </p>
            </CardWrapper>
          );
        })}
      </div>
    </div>
  );
};
