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 } from 'lucide-react';
import { Button, Card, Badge } from '../ui';
import {
  subscriptionService,
  type PlanMetadata,
  type SubscriptionTier,
  SUBSCRIPTION_TIERS
} from '../../api';
import { getRegisterUrl } from '../../utils/navigation';

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();
  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);

  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-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:text-[var(--text-primary)]'
            }`}
          >
            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:text-[var(--text-primary)]'
            }`}
          >
            Anual
            <span className="text-xs font-bold text-green-600 dark:text-green-400">
              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
                ${mode === 'selection' ? '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-[var(--color-primary)] via-[var(--color-primary)] to-[var(--color-primary-dark)] shadow-2xl transform scale-105 z-10'
                    : 'bg-[var(--bg-secondary)] border-2 border-[var(--border-primary)] hover:border-[var(--color-primary)]/30 hover:shadow-xl hover:-translate-y-1'
                }
              `}
            >
              {/* 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 leading-relaxed ${isPopular ? 'text-white/90' : 'text-[var(--text-secondary)]'}`}>
                  {plan.tagline}
                </p>
              </div>

              {/* Pricing */}
              <div className="mb-8">
                <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/80' : '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 && (
                  <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)]'
                  }`}>
                    3 meses gratis
                  </div>
                )}
              </div>

              {/* Key Limits */}
              <div className={`mb-6 p-4 rounded-lg ${
                isPopular ? 'bg-white/10' : isSelected ? 'bg-[var(--color-primary)]/5' : 'bg-[var(--bg-primary)]'
              }`}>
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div>
                    <span className={isPopular ? 'text-white/80' : 'text-[var(--text-secondary)]'}>Usuarios:</span>
                    <span className={`font-semibold ml-2 ${isPopular ? 'text-white' : isSelected ? 'text-[var(--color-primary)]' : 'text-[var(--text-primary)]'}`}>
                      {plan.limits.users || 'Ilimitado'}
                    </span>
                  </div>
                  <div>
                    <span className={isPopular ? 'text-white/80' : 'text-[var(--text-secondary)]'}>Ubicaciones:</span>
                    <span className={`font-semibold ml-2 ${isPopular ? 'text-white' : isSelected ? 'text-[var(--color-primary)]' : 'text-[var(--text-primary)]'}`}>
                      {plan.limits.locations || 'Ilimitado'}
                    </span>
                  </div>
                  <div>
                    <span className={isPopular ? 'text-white/80' : 'text-[var(--text-secondary)]'}>Productos:</span>
                    <span className={`font-semibold ml-2 ${isPopular ? 'text-white' : isSelected ? 'text-[var(--color-primary)]' : 'text-[var(--text-primary)]'}`}>
                      {plan.limits.products || 'Ilimitado'}
                    </span>
                  </div>
                  <div>
                    <span className={isPopular ? 'text-white/80' : 'text-[var(--text-secondary)]'}>Pronósticos/día:</span>
                    <span className={`font-semibold ml-2 ${isPopular ? 'text-white' : isSelected ? 'text-[var(--color-primary)]' : 'text-[var(--text-primary)]'}`}>
                      {plan.limits.forecasts_per_day || 'Ilimitado'}
                    </span>
                  </div>
                </div>
              </div>

              {/* Features List */}
              <div className={`space-y-3 mb-8 max-h-80 overflow-y-auto pr-2 scrollbar-thin`}>
                {plan.features.slice(0, 8).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>
                ))}
                {plan.features.length > 8 && (
                  <p className={`text-sm italic ${isPopular ? 'text-white/70' : 'text-[var(--text-secondary)]'}`}>
                    Y {plan.features.length - 8} características más...
                  </p>
                )}
              </div>

              {/* Support */}
              <div className={`mb-6 text-sm text-center border-t pt-4 ${
                isPopular ? 'text-white/80 border-white/20' : 'text-[var(--text-secondary)] border-[var(--border-primary)]'
              }`}>
                {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'}
                  <ArrowRight className="ml-2 w-4 h-4" />
                </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/70' : 'text-[var(--text-secondary)]'}`}>
                3 meses gratis • Tarjeta requerida para validación
              </p>
            </CardWrapper>
          );
        })}
      </div>
    </div>
  );
};
