import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { Check, Star, Loader, Users, MapPin, Package } from 'lucide-react';
import { Button, Card } from '../ui';
import {
  subscriptionService,
  type PlanMetadata,
  type SubscriptionTier,
  SUBSCRIPTION_TIERS
} from '../../api';
import { getRegisterUrl } from '../../utils/navigation';

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

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

export const SubscriptionPricingCards: React.FC<SubscriptionPricingCardsProps> = ({
  mode = 'landing',
  selectedPlan,
  onPlanSelect,
  showPilotBanner = false,
  pilotCouponCode,
  pilotTrialMonths = 3,
  showComparison = false,
  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);

  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(t('ui.error_loading'));
    } 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 formatFeatureName = (feature: string): string => {
    const translatedFeature = t(`features.${feature}`);
    return translatedFeature.startsWith('features.')
      ? feature.replace(/_/g, ' ')
      : translatedFeature;
  };

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

  // Get top 3 benefits for each tier (business outcomes)
  const getTopBenefits = (tier: SubscriptionTier, plan: PlanMetadata): string[] => {
    // Use hero_features if available, otherwise use first 3 features
    return plan.hero_features?.slice(0, 3) || plan.features.slice(0, 3);
  };

  // Format limit display with emoji and user-friendly text
  const formatLimit = (value: number | string | null | undefined, unlimitedKey: string): string => {
    if (!value || value === -1 || value === 'unlimited') {
      return t(unlimitedKey);
    }
    return value.toString();
  };

  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)]">{t('ui.loading')}</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}>{t('ui.retry')}</Button>
      </div>
    );
  }

  return (
    <div className={className}>
      {/* Pilot Program Banner */}
      {showPilotBanner && pilotCouponCode && (
        <Card className="p-6 mb-8 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">
                {t('ui.pilot_program_active')}
              </h3>
              <p className="text-sm text-amber-800 dark:text-amber-200"
                 dangerouslySetInnerHTML={{
                   __html: t('ui.pilot_program_description', { count: pilotTrialMonths })
                     .replace('{count}', `<strong>${pilotTrialMonths}</strong>`)
                     .replace('20%', '<strong>20%</strong>')
                 }}
              />
            </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>

      {/* Simplified Plans Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 items-start lg:items-stretch">
        {Object.entries(plans).map(([tier, plan]) => {
          const price = getPrice(plan);
          const savings = getSavings(plan);
          const isPopular = plan.popular;
          const tierKey = tier as SubscriptionTier;
          const topBenefits = getTopBenefits(tierKey, plan);

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

          return (
            <CardWrapper
              key={tier}
              {...cardProps}
              className={`
                relative rounded-2xl p-8 transition-all duration-300 block no-underline
                ${mode === 'settings' ? 'cursor-pointer' : mode === 'landing' ? 'cursor-pointer' : ''}
                ${isPopular
                  ? 'bg-gradient-to-br from-blue-600 to-blue-800 shadow-xl ring-2 ring-blue-400 lg:scale-105 lg:z-10'
                  : 'bg-[var(--bg-secondary)] border-2 border-[var(--border-primary)] hover:border-[var(--color-primary)] hover:shadow-lg'
                }
              `}
            >
              {/* Popular Badge */}
              {isPopular && (
                <div className="absolute -top-4 left-1/2 transform -translate-x-1/2">
                  <div className="bg-gradient-to-r from-green-500 to-emerald-600 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" />
                    {t('ui.most_popular')}
                  </div>
                </div>
              )}

              {/* Plan Header */}
              <div className="mb-6">
                <h3 className={`text-2xl font-bold mb-2 ${isPopular ? 'text-white' : 'text-[var(--text-primary)]'}`}>
                  {plan.name}
                </h3>
                <p className={`text-sm ${isPopular ? 'text-white/90' : 'text-[var(--text-secondary)]'}`}>
                  {plan.tagline_key ? t(plan.tagline_key) : plan.tagline || ''}
                </p>
              </div>

              {/* Price */}
              <div className="mb-6">
                <div className="flex items-baseline">
                  <span className={`text-4xl font-bold ${isPopular ? 'text-white' : 'text-[var(--text-primary)]'}`}>
                    {subscriptionService.formatPrice(price)}
                  </span>
                  <span className={`ml-2 text-lg ${isPopular ? 'text-white/80' : 'text-[var(--text-secondary)]'}`}>
                    /{billingCycle === 'monthly' ? t('ui.per_month') : t('ui.per_year')}
                  </span>
                </div>

                {/* Trial Badge - Always Visible */}
                <div className={`mt-3 px-3 py-1.5 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'
                }`}>
                  {savings
                    ? t('ui.save_amount', { amount: subscriptionService.formatPrice(savings.savingsAmount) })
                    : showPilotBanner
                      ? t('billing.free_months', { count: pilotTrialMonths })
                      : t('billing.free_trial_days', { count: plan.trial_days })
                  }
                </div>
              </div>

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

              {/* Feature Inheritance Indicator */}
              {tier === SUBSCRIPTION_TIERS.PROFESSIONAL && (
                <div className={`mb-5 px-4 py-3 rounded-xl transition-all ${
                  isPopular
                    ? 'bg-gradient-to-r from-white/20 to-white/10 border-2 border-white/40 shadow-lg'
                    : 'bg-gradient-to-r from-blue-500/10 to-blue-600/5 border-2 border-blue-400/30 dark:from-blue-400/10 dark:to-blue-500/5 dark:border-blue-400/30'
                }`}>
                  <p className={`text-xs font-bold uppercase tracking-wide text-center ${
                    isPopular ? 'text-white drop-shadow-sm' : 'text-blue-600 dark:text-blue-300'
                  }`}>
                    ✓ {t('ui.feature_inheritance_professional')}
                  </p>
                </div>
              )}
              {tier === SUBSCRIPTION_TIERS.ENTERPRISE && (
                <div className={`mb-5 px-4 py-3 rounded-xl transition-all ${
                  isPopular
                    ? 'bg-gradient-to-r from-white/20 to-white/10 border-2 border-white/40 shadow-lg'
                    : 'bg-gradient-to-r from-gray-700/20 to-gray-800/10 border-2 border-gray-600/40 dark:from-gray-600/20 dark:to-gray-700/10 dark:border-gray-500/40'
                }`}>
                  <p className={`text-xs font-bold uppercase tracking-wide text-center ${
                    isPopular ? 'text-white drop-shadow-sm' : 'text-gray-700 dark:text-gray-300'
                  }`}>
                    ✓ {t('ui.feature_inheritance_enterprise')}
                  </p>
                </div>
              )}

              {/* Top 3 Benefits + Key Limits */}
              <div className="space-y-3 mb-6">
                {/* Business Benefits */}
                {topBenefits.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-green-500'
                      }`}>
                        <Check className={`w-3 h-3 ${isPopular ? 'text-blue-600' : 'text-white'}`} />
                      </div>
                    </div>
                    <span className={`ml-3 text-sm font-medium ${isPopular ? 'text-white' : 'text-[var(--text-primary)]'}`}>
                      {formatFeatureName(feature)}
                    </span>
                  </div>
                ))}

                {/* Key Limits (Users, Locations, Products) */}
                <div className={`pt-4 mt-4 border-t space-y-2 ${isPopular ? 'border-white/20' : 'border-[var(--border-primary)]'}`}>
                  <div className="flex items-center text-sm">
                    <Users className={`w-4 h-4 mr-2 ${isPopular ? 'text-white/80' : 'text-[var(--text-secondary)]'}`} />
                    <span className={`font-medium ${isPopular ? 'text-white' : 'text-[var(--text-primary)]'}`}>
                      {formatLimit(plan.limits.users, 'limits.users_unlimited')} {t('limits.users_label', 'usuarios')}
                    </span>
                  </div>
                  <div className="flex items-center text-sm">
                    <MapPin className={`w-4 h-4 mr-2 ${isPopular ? 'text-white/80' : 'text-[var(--text-secondary)]'}`} />
                    <span className={`font-medium ${isPopular ? 'text-white' : 'text-[var(--text-primary)]'}`}>
                      {formatLimit(plan.limits.locations, 'limits.locations_unlimited')} {t('limits.locations_label', 'ubicaciones')}
                    </span>
                  </div>
                  <div className="flex items-center text-sm">
                    <Package className={`w-4 h-4 mr-2 ${isPopular ? 'text-white/80' : 'text-[var(--text-secondary)]'}`} />
                    <span className={`font-medium ${isPopular ? 'text-white' : 'text-[var(--text-primary)]'}`}>
                      {formatLimit(plan.limits.products, 'limits.products_unlimited')} {t('limits.products_label', 'productos')}
                    </span>
                  </div>
                </div>
              </div>

              {/* CTA Button */}
              <Button
                className={`w-full py-4 text-base font-semibold transition-all ${
                  isPopular
                    ? 'bg-white text-blue-600 hover:bg-gray-100'
                    : 'bg-[var(--color-primary)] text-white hover:bg-[var(--color-primary-dark)]'
                }`}
                onClick={(e) => {
                  if (mode === 'settings') {
                    e.preventDefault();
                    e.stopPropagation();
                    handlePlanAction(tier, plan);
                  }
                }}
              >
                {t('ui.start_free_trial')}
              </Button>

              {/* Footer */}
              <p className={`text-xs text-center mt-3 ${isPopular ? 'text-white/80' : 'text-[var(--text-secondary)]'}`}>
                {showPilotBanner
                  ? t('ui.free_trial_footer', { months: pilotTrialMonths })
                  : t('ui.free_trial_footer', { months: 0 })
                }
              </p>
            </CardWrapper>
          );
        })}
      </div>

      {/* Comparison Link */}
      {showComparison && mode === 'landing' && (
        <div className="text-center mt-8">
          <Link
            to="#comparison"
            className="text-[var(--color-primary)] hover:underline text-sm font-medium"
          >
            {t('ui.view_full_comparison', 'Ver comparación completa de características →')}
          </Link>
        </div>
      )}
    </div>
  );
};
