import React, { useState, useEffect } from 'react';
import { Crown, Users, MapPin, Package, TrendingUp, RefreshCw, AlertCircle, CheckCircle, ArrowRight, Star, ExternalLink, Download, CreditCard, X, Activity, Database, Zap, HardDrive, ShoppingCart, ChefHat, Settings, Sparkles, ChevronDown, ChevronUp, AlertTriangle, Info, HelpCircle } from 'lucide-react';
import { Button, Card, Badge, Modal } from '../../../../components/ui';
import { DialogModal } from '../../../../components/ui/DialogModal/DialogModal';
import { PageHeader } from '../../../../components/layout';
import { useAuthUser } from '../../../../stores/auth.store';
import { useCurrentTenant } from '../../../../stores';
import { showToast } from '../../../../utils/toast';
import { subscriptionService, type UsageSummary, type AvailablePlans } from '../../../../api';
import { useSubscriptionEvents } from '../../../../contexts/SubscriptionEventsContext';
import { SubscriptionPricingCards } from '../../../../components/subscription/SubscriptionPricingCards';
import { PlanComparisonTable, ROICalculator, UsageMetricCard } from '../../../../components/subscription';
import { PaymentMethodUpdateModal } from '../../../../components/subscription/PaymentMethodUpdateModal';
import { useSubscription } from '../../../../hooks/useSubscription';
import {
  trackSubscriptionPageViewed,
  trackUpgradeCTAClicked,
  trackUsageMetricViewed
} from '../../../../utils/subscriptionAnalytics';
import { useTranslation } from 'react-i18next';
import { useQueryClient } from '@tanstack/react-query';

// New simplified components for the redesign

const SubscriptionStatusBanner: React.FC<{
  planName: string;
  status: string;
  nextBilling: string;
  cost: string;
  onUpgrade: () => void;
  onManagePayment: () => void;
  showUpgradeButton: boolean;
  isTrial?: boolean;
  trialEndsAt?: string;
  trialDaysRemaining?: number;
  isPilot?: boolean;
}> = ({ planName, status, nextBilling, cost, onUpgrade, onManagePayment, showUpgradeButton, isTrial, trialEndsAt, trialDaysRemaining, isPilot }) => {

  // Determine if we should show trial information
  const showTrialInfo = isTrial && trialEndsAt;
  const showPilotInfo = isPilot;

  return (
    <Card className={`p-6 mb-6 ${showTrialInfo || showPilotInfo
      ? 'bg-gradient-to-r from-blue-50 to-cyan-50 dark:from-blue-900/30 dark:to-cyan-900/30 border-2 border-blue-300 dark:border-blue-600'
      : 'bg-gradient-to-r from-blue-50 to-purple-50 dark:from-blue-900/20 dark:to-purple-900/20 border-2 border-blue-200 dark:border-blue-700'}`}
    >
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 items-center">
        <div>
          <h3 className="text-lg font-semibold text-[var(--text-primary)] flex items-center gap-2">
            <Crown className="w-5 h-5 text-yellow-500" />
            {planName} {showPilotInfo && <span className="text-blue-600 dark:text-blue-400">(Programa Piloto)</span>}
            {!showPilotInfo && showTrialInfo && <span className="text-blue-600 dark:text-blue-400">(Prueba Gratis)</span>}
          </h3>
          <Badge variant={showPilotInfo ? 'info' : showTrialInfo ? 'info' : status === 'active' ? 'success' : 'default'} className="mt-2">
            {showPilotInfo ? 'Piloto Activo' : showTrialInfo ? `En Prueba (${trialDaysRemaining} días)` : status === 'active' ? 'Activo' : status}
          </Badge>
        </div>

        <div className="text-center">
          <p className="text-sm text-[var(--text-secondary)]">{showPilotInfo ? 'Fin del Piloto' : showTrialInfo ? 'Fin de la Prueba' : 'Próxima Facturación'}</p>
          <p className="font-semibold text-[var(--text-primary)]">{showPilotInfo ? trialEndsAt : showTrialInfo ? trialEndsAt : nextBilling}</p>
        </div>

        <div className="text-center">
          <p className="text-sm text-[var(--text-secondary)]">Costo Mensual</p>
          <p className="font-semibold text-[var(--text-primary)] text-lg">
            {cost} {showPilotInfo && <span className="text-xs text-blue-600 dark:text-blue-400">(después del periodo piloto)</span>}
            {!showPilotInfo && showTrialInfo && <span className="text-xs text-blue-600 dark:text-blue-400">(después de la prueba)</span>}
          </p>
        </div>

        <div className="flex flex-col gap-2">
          {showPilotInfo || showTrialInfo ? (
            <>
              <Button onClick={onUpgrade} variant="primary" size="sm" className="w-full bg-gradient-to-r from-blue-600 to-cyan-600 hover:from-blue-700 hover:to-cyan-700">
                <ArrowRight className="w-4 h-4 mr-2" />
                Actualizar Ahora
              </Button>
              <Button onClick={onManagePayment} variant="outline" size="sm" className="w-full">
                <CreditCard className="w-4 h-4 mr-2" />
                Configurar Pago
              </Button>
            </>
          ) : (
            <>
              <Button onClick={onManagePayment} variant="outline" size="sm" className="w-full">
                <CreditCard className="w-4 h-4 mr-2" />
                Gestionar Pago
              </Button>
              {showUpgradeButton && (
                <Button onClick={onUpgrade} variant="primary" size="sm" className="w-full">
                  <ArrowRight className="w-4 h-4 mr-2" />
                  Ver Planes
                </Button>
              )}
            </>
          )}
        </div>
      </div>

      {/* Pilot/Trial Countdown Banner */}
      {(showPilotInfo || showTrialInfo) && (
        <div className="mt-4 p-4 bg-gradient-to-r from-blue-600/10 to-cyan-600/10 border border-blue-300/50 rounded-lg">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-blue-500/20 rounded-lg border border-blue-500/30 flex-shrink-0">
              <Sparkles className="w-5 h-5 text-blue-500" />
            </div>
            <div className="flex-1">
              <p className="text-sm font-medium text-blue-700 dark:text-blue-300">
                {showPilotInfo
                  ? `¡Eres parte de nuestro programa piloto! Tu acceso gratuito termina en <strong>${trialDaysRemaining} días</strong>.`
                  : `¡Disfruta de tu periodo de prueba! Tu acceso gratuito termina en <strong>${trialDaysRemaining} días</strong>.`
                }
              </p>
            </div>
            <Button onClick={onUpgrade} variant="ghost" size="sm" className="text-blue-600 dark:text-blue-400 hover:bg-blue-500/10">
              <ArrowRight className="w-4 h-4 mr-1" />
              Actualizar
            </Button>
          </div>
        </div>
      )}
    </Card>
  );
};

const UsageAlertCard: React.FC<{
  metric: string;
  current: number;
  limit: number | null;
  percentage: number;
  daysUntilLimit: number | null;
  onUpgrade: () => void;
  icon: React.ReactNode;
}> = ({ metric, current, limit, percentage, daysUntilLimit, onUpgrade, icon }) => {
  const isUnlimited = limit === null || limit === -1;
  const isCritical = percentage >= 90;
  const isWarning = percentage >= 80 && percentage < 90;

  const getStatusColor = () => {
    if (isCritical) return 'red';
    if (isWarning) return 'yellow';
    return 'green';
  };

  const statusColor = getStatusColor();

  const colorClasses = {
    red: {
      bg: 'bg-red-50 dark:bg-red-900/20',
      border: 'border-red-200 dark:border-red-700',
      text: 'text-red-600 dark:text-red-400',
      icon: 'text-red-500'
    },
    yellow: {
      bg: 'bg-yellow-50 dark:bg-yellow-900/20',
      border: 'border-yellow-200 dark:border-yellow-700',
      text: 'text-yellow-600 dark:text-yellow-400',
      icon: 'text-yellow-500'
    },
    green: {
      bg: 'bg-green-50 dark:bg-green-900/20',
      border: 'border-green-200 dark:border-green-700',
      text: 'text-green-600 dark:text-green-400',
      icon: 'text-green-500'
    }
  };

  const colors = colorClasses[statusColor];

  return (
    <Card className={`${colors.bg} ${colors.border} border-2 p-4`}>
      <div className="flex items-start gap-3">
        <div className={`p-2 rounded-lg ${colors.bg} ${colors.border} border flex-shrink-0`}>
          {React.cloneElement(icon as React.ReactElement, { className: `w-5 h-5 ${colors.icon}` })}
        </div>
        
        <div className="flex-1">
          <div className="flex items-center justify-between mb-1">
            <h4 className="font-semibold text-[var(--text-primary)]">{metric}</h4>
            {!isUnlimited && (
              <Badge variant={statusColor === 'red' ? 'danger' : statusColor === 'yellow' ? 'warning' : 'success'}>
                {Math.round(percentage)}%
              </Badge>
            )}
          </div>
          
          <div className="flex items-baseline gap-2 mb-2">
            <span className="text-2xl font-bold text-[var(--text-primary)]">{current}</span>
            <span className="text-sm text-[var(--text-secondary)]">
              / {isUnlimited ? '∞' : limit}
            </span>
          </div>
          
          {!isUnlimited && (
            <div className="w-full h-2 bg-[var(--bg-tertiary)] rounded-full overflow-hidden mb-2">
              <div
                className={`h-full transition-all duration-300 ${colors.bg.replace('bg-', 'bg-').replace('dark:', '')} ${
                  isCritical ? 'animate-pulse' : ''
                }`}
                style={{ width: `${percentage}%` }}
              />
            </div>
          )}
          
          {isWarning && daysUntilLimit && (
            <p className={`text-xs ${colors.text} font-medium`}>
              {daysUntilLimit > 0 
                ? `Alcanzarás el límite en ~${daysUntilLimit} días`
                : 'Has alcanzado tu límite'}
            </p>
          )}
          
          {isWarning && (
            <Button onClick={onUpgrade} variant="primary" size="sm" className="mt-3 w-full">
              <ArrowRight className="w-4 h-4 mr-2" />
              Actualizar Plan
            </Button>
          )}
        </div>
      </div>
    </Card>
  );
};

const SimpleMetricCard: React.FC<{
  icon: React.ReactNode;
  label: string;
  value: string;
  status: 'safe' | 'warning' | 'critical';
}> = ({ icon, label, value, status }) => {
  const statusColors = {
    safe: {
      bg: 'bg-green-50 dark:bg-green-900/20',
      border: 'border-green-200 dark:border-green-700',
      text: 'text-green-600 dark:text-green-400'
    },
    warning: {
      bg: 'bg-yellow-50 dark:bg-yellow-900/20',
      border: 'border-yellow-200 dark:border-yellow-700',
      text: 'text-yellow-600 dark:text-yellow-400'
    },
    critical: {
      bg: 'bg-red-50 dark:bg-red-900/20',
      border: 'border-red-200 dark:border-red-700',
      text: 'text-red-600 dark:text-red-400'
    }
  };

  const colors = statusColors[status];

  return (
    <div className={`${colors.bg} ${colors.border} border p-4 rounded-lg`}>
      <div className="flex items-center gap-3">
        <div className="p-2 rounded-lg bg-[var(--bg-secondary)] flex-shrink-0">
          {icon}
        </div>
        <div className="flex-1">
          <p className="text-sm text-[var(--text-secondary)] mb-1">{label}</p>
          <p className="font-semibold text-[var(--text-primary)]">{value}</p>
        </div>
        {status !== 'safe' && (
          <div className="flex-shrink-0">
            {status === 'warning' && <AlertTriangle className={`w-5 h-5 ${colors.text}`} />}
            {status === 'critical' && <AlertCircle className={`w-5 h-5 ${colors.text}`} />}
          </div>
        )}
      </div>
    </div>
  );
};

const CollapsibleSection: React.FC<{
  title: string;
  icon: React.ReactNode;
  isOpen: boolean;
  onToggle: () => void;
  children: React.ReactNode;
  showAlert?: boolean;
}> = ({ title, icon, isOpen, onToggle, children, showAlert = false }) => {
  return (
    <Card className={`mb-4 ${showAlert ? 'border-2 border-yellow-200 dark:border-yellow-700 bg-yellow-50 dark:bg-yellow-900/20' : ''}`}>
      <button
        onClick={onToggle}
        className="w-full flex items-center justify-between p-4 hover:bg-[var(--bg-secondary)] transition-colors"
      >
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-[var(--bg-secondary)] flex-shrink-0">
            {icon}
          </div>
          <h3 className="text-lg font-semibold text-[var(--text-primary)]">{title}</h3>
          {showAlert && (
            <Badge variant="warning" className="ml-2">
              <AlertTriangle className="w-3 h-3 mr-1" />
              Requiere Atención
            </Badge>
          )}
        </div>
        {isOpen ? <ChevronUp className="w-5 h-5 text-[var(--text-secondary)]" /> : <ChevronDown className="w-5 h-5 text-[var(--text-secondary)]" />}
      </button>
      
      {isOpen && (
        <div className="p-4 pt-0 border-t border-[var(--border-primary)]">
          {children}
        </div>
      )}
    </Card>
  );
};

const SubscriptionPageRedesign: React.FC = () => {
  const user = useAuthUser();
  const currentTenant = useCurrentTenant();
  const { notifySubscriptionChanged } = useSubscriptionEvents();
  const { t } = useTranslation('subscription');
  const queryClient = useQueryClient();

  const [usageSummary, setUsageSummary] = useState<UsageSummary | null>(null);
  const [availablePlans, setAvailablePlans] = useState<AvailablePlans | null>(null);
  const [subscriptionLoading, setSubscriptionLoading] = useState(false);
  const [upgradeDialogOpen, setUpgradeDialogOpen] = useState(false);
  const [selectedPlan, setSelectedPlan] = useState<string>('');
  const [upgrading, setUpgrading] = useState(false);
  const [cancellationDialogOpen, setCancellationDialogOpen] = useState(false);
  const [cancelling, setCancelling] = useState(false);
  const [invoices, setInvoices] = useState<any[]>([]);
  const [invoicesLoading, setInvoicesLoading] = useState(false);
  const [invoicesLoaded, setInvoicesLoaded] = useState(false);
  const [paymentMethodModalOpen, setPaymentMethodModalOpen] = useState(false);
  const [currentPaymentMethod, setCurrentPaymentMethod] = useState<{
    brand?: string;
    last4?: string;
    exp_month?: number;
    exp_year?: number;
  } | null>(null);

  // Billing cycle state (monthly/yearly)
  const [billingCycle, setBillingCycle] = useState<'monthly' | 'yearly'>('monthly');

  // Section visibility states
  const [showUsage, setShowUsage] = useState(false);
  const [showBilling, setShowBilling] = useState(false);
  const [showPlans, setShowPlans] = useState(false);
  const [showComparison, setShowComparison] = useState(false);
  const [showROI, setShowROI] = useState(false);

  // Use new subscription hook for usage forecast data
  const { subscription: subscriptionData, usage: forecastUsage, forecast } = useSubscription();

  // Auto-expand sections with alerts
  useEffect(() => {
    if (forecastUsage && forecastUsage.highUsageMetrics && forecastUsage.highUsageMetrics.length > 0) {
      setShowUsage(true);
    }
  }, [forecastUsage]);

  // Load subscription data on component mount
  React.useEffect(() => {
    loadSubscriptionData();
    loadInvoices();
    loadCurrentPaymentMethod();
  }, []);

  // Add function to load current payment method
  const loadCurrentPaymentMethod = async () => {
    const tenantId = currentTenant?.id || user?.tenant_id;

    if (!tenantId) {
      return;
    }

    try {
      // Try to get payment method from usage summary first
      // If not available, we'll need to add an API endpoint
      // For now, we'll use a fallback approach
      
      // Check if we have payment method info in the usage summary
      // This is a temporary solution until we add proper API support
      if (usageSummary && (usageSummary as any).payment_method) {
        setCurrentPaymentMethod((usageSummary as any).payment_method);
      } else {
        // Fallback: Try to fetch from a potential endpoint
        // This will fail gracefully if endpoint doesn't exist
        try {
          const paymentMethod = await subscriptionService.getCurrentPaymentMethod(tenantId);
          if (paymentMethod) {
            setCurrentPaymentMethod(paymentMethod);
          }
        } catch (error) {
          console.log('Payment method endpoint not available, using fallback');
          // If no payment method is available, we'll show the "Add Payment Method" flow
        }
      }
    } catch (error) {
      console.error('Error loading payment method:', error);
    }
  };

  // Track page view
  useEffect(() => {
    if (usageSummary) {
      trackSubscriptionPageViewed(usageSummary.plan);
    }
  }, [usageSummary]);

  // Track high usage metrics
  useEffect(() => {
    if (forecast?.metrics) {
      forecast.metrics.forEach(metric => {
        if (metric.usage_percentage >= 80) {
          trackUsageMetricViewed(
            metric.metric,
            metric.current,
            metric.limit,
            metric.usage_percentage,
            metric.days_until_breach
          );
        }
      });
    }
  }, [forecast]);

  const loadSubscriptionData = async () => {
    const tenantId = currentTenant?.id || user?.tenant_id;

    if (!tenantId) {
      showToast.error('No se encontró información del tenant');
      return;
    }

    try {
      setSubscriptionLoading(true);
      const [usage, plans] = await Promise.all([
        subscriptionService.getUsageSummary(tenantId),
        subscriptionService.fetchAvailablePlans()
      ]);

      if (!usage || !usage.usage) {
        throw new Error('No subscription found. Please contact support or create a new subscription.');
      }

      setUsageSummary(usage);
      setAvailablePlans(plans);
      // Initialize billing cycle from current subscription
      if (usage.billing_cycle) {
        setBillingCycle(usage.billing_cycle);
      }
    } catch (error) {
      console.error('Error loading subscription data:', error);
      showToast.error(
        error instanceof Error && error.message.includes('No subscription')
          ? error.message
          : "No se pudo cargar la información de suscripción. Por favor, contacte con soporte."
      );
    } finally {
      setSubscriptionLoading(false);
    }
  };

  const handleUpgradeClick = (planKey: string, source: string = 'pricing_cards') => {
    if (usageSummary) {
      trackUpgradeCTAClicked(usageSummary.plan, planKey, source);
    }
    setSelectedPlan(planKey);
    setUpgradeDialogOpen(true);
  };

  const handleUpgradeConfirm = async () => {
    const tenantId = currentTenant?.id || user?.tenant_id;

    if (!tenantId || !selectedPlan) {
      showToast.error('Información de tenant no disponible');
      return;
    }

    try {
      setUpgrading(true);

      // Step 1: Validate the upgrade
      const validation = await subscriptionService.validatePlanUpgrade(
        tenantId,
        selectedPlan
      );

      if (!validation.can_upgrade) {
        showToast.error(validation.reason || 'No se puede actualizar el plan');
        return;
      }

      // Step 2: Execute the upgrade (uses current billing cycle)
      const result = await subscriptionService.upgradePlan(
        tenantId,
        selectedPlan,
        billingCycle  // Pass the currently selected billing cycle
      );

      if (result.success) {
        // Show appropriate success message based on trial status
        if (result.is_trialing && result.trial_preserved) {
          showToast.success(
            `¡Plan actualizado a ${result.new_plan}! Tu período de prueba continúa hasta ${
              result.trial_ends_at ? new Date(result.trial_ends_at).toLocaleDateString('es-ES') : 'su fecha original'
            }. Al finalizar, se aplicará el precio del nuevo plan.`
          );
        } else {
          showToast.success(result.message || `¡Plan actualizado exitosamente a ${result.new_plan}!`);
        }

        // Step 3: Invalidate caches to refresh UI
        subscriptionService.invalidateCache();

        // Step 4: Refresh subscription data from server
        if (result.requires_token_refresh) {
          // Force a fresh fetch of subscription data
          await subscriptionService.getUsageSummary(tenantId).catch(() => {});
        }

        // Step 5: Invalidate React Query caches
        await queryClient.invalidateQueries({ queryKey: ['subscription-usage'] });
        await queryClient.invalidateQueries({ queryKey: ['tenant'] });
        await queryClient.invalidateQueries({ queryKey: ['subscription'] });

        // Step 6: Notify other components about the change
        notifySubscriptionChanged();

        // Step 7: Reload subscription data for this page
        await loadSubscriptionData();

        // Step 8: Close dialog and reset state
        setUpgradeDialogOpen(false);
        setSelectedPlan('');
      } else {
        showToast.error('Error al cambiar el plan');
      }
    } catch (error) {
      console.error('Error upgrading plan:', error);
      const errorMessage = error instanceof Error ? error.message : 'Error al procesar el cambio de plan';
      showToast.error(errorMessage);
    } finally {
      setUpgrading(false);
    }
  };

  const handleCancellationClick = () => {
    setCancellationDialogOpen(true);
  };

  const handleCancelSubscription = async () => {
    const tenantId = currentTenant?.id || user?.tenant_id;

    if (!tenantId) {
      showToast.error('Información de tenant no disponible');
      return;
    }

    try {
      setCancelling(true);

      const result = await subscriptionService.cancelSubscription(tenantId, 'User requested cancellation');

      if (result.success) {
        const daysRemaining = result.days_remaining;
        const effectiveDate = new Date(result.cancellation_effective_date).toLocaleDateString('es-ES', {
          year: 'numeric',
          month: 'long',
          day: 'numeric'
        });

        showToast.success(
          `Suscripción cancelada. Acceso de solo lectura a partir del ${effectiveDate} (${daysRemaining} días restantes)`
        );
      }

      await loadSubscriptionData();
      setCancellationDialogOpen(false);
    } catch (error) {
      console.error('Error cancelling subscription:', error);
      showToast.error('Error al cancelar la suscripción');
    } finally {
      setCancelling(false);
    }
  };

  const loadInvoices = async () => {
    const tenantId = currentTenant?.id || user?.tenant_id;

    if (!tenantId) {
      return;
    }

    try {
      setInvoicesLoading(true);
      const fetchedInvoices = await subscriptionService.getInvoices(tenantId);

      // Ensure fetchedInvoices is an array before setting state
      const validatedInvoices = Array.isArray(fetchedInvoices) ? fetchedInvoices : [];
      setInvoices(validatedInvoices);
      setInvoicesLoaded(true);
    } catch (error) {
      console.error('Error loading invoices:', error);
      // Set invoices to empty array in case of error to prevent slice error
      setInvoices([]);
      if (invoicesLoaded) {
        showToast.error('Error al cargar las facturas');
      }
    } finally {
      setInvoicesLoading(false);
    }
  };

  const handleDownloadInvoice = (invoice: any) => {
    if (invoice.invoice_pdf) {
      window.open(invoice.invoice_pdf, '_blank');
    } else if (invoice.hosted_invoice_url) {
      window.open(invoice.hosted_invoice_url, '_blank');
    } else {
      showToast.warning('No hay PDF disponible para esta factura');
    }
  };

  // Helper function to determine metric status
  const getMetricStatus = (usagePercentage: number): 'safe' | 'warning' | 'critical' => {
    if (usagePercentage >= 90) return 'critical';
    if (usagePercentage >= 80) return 'warning';
    return 'safe';
  };

  // Helper function to format limit display
  const formatLimitDisplay = (current: number, limit: number | null | undefined, unlimitedText: string): string => {
    if (limit === null || limit === -1 || limit === undefined) {
      return `${current} (${unlimitedText})`;
    }
    return `${current}/${limit}`;
  };

  if (subscriptionLoading) {
    return (
      <div className="p-6 space-y-6">
        <PageHeader
          title="Suscripción y Facturación"
          description="Gestiona tu suscripción, uso de recursos y facturación"
        />
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="flex flex-col items-center gap-4">
            <RefreshCw className="w-8 h-8 animate-spin text-[var(--color-primary)]" />
            <p className="text-[var(--text-secondary)]">Cargando información de suscripción...</p>
          </div>
        </div>
      </div>
    );
  }

  if (!usageSummary || !availablePlans) {
    return (
      <div className="p-6 space-y-6">
        <PageHeader
          title="Suscripción y Facturación"
          description="Gestiona tu suscripción, uso de recursos y facturación"
        />
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="flex flex-col items-center gap-4">
            <AlertCircle className="w-12 h-12 text-[var(--text-tertiary)]" />
            <div className="text-center">
              <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">No se pudo cargar la información</h3>
              <p className="text-[var(--text-secondary)] mb-4">Hubo un problema al cargar los datos de suscripción</p>
              <Button onClick={loadSubscriptionData} variant="primary">
                <RefreshCw className="w-4 h-4 mr-2" />
                Reintentar
              </Button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Check if there are any high usage metrics
  const hasHighUsageMetrics = forecastUsage && forecastUsage.highUsageMetrics && forecastUsage.highUsageMetrics.length > 0;

  // Determine if this is a pilot subscription based on characteristics
  // Pilot subscriptions have extended trial periods (typically 90 days from PILOT2025 coupon)
  // compared to regular trials (typically 14 days), so we check for longer trial periods
  const isPilotSubscription = (usageSummary.status === 'trialing' || 
                              (usageSummary.trial_ends_at && new Date(usageSummary.trial_ends_at) > new Date())) &&
                              usageSummary.trial_ends_at &&
                              // Check if trial period is longer than typical trial (e.g., > 60 days indicates pilot)
                              (new Date(usageSummary.trial_ends_at).getTime() - new Date().getTime()) > (60 * 24 * 60 * 60 * 1000); // 60+ days

  return (
    <div className="p-6 space-y-6">
      <PageHeader
        title="Suscripción y Facturación"
        description="Gestiona tu suscripción, uso de recursos y facturación"
      />

      {/* NEW: Subscription Status Banner - Always Visible */}
      <SubscriptionStatusBanner
        planName={usageSummary.plan.charAt(0).toUpperCase() + usageSummary.plan.slice(1)}
        status={usageSummary.status}
        nextBilling={new Date(usageSummary.next_billing_date).toLocaleDateString('es-ES', {
          day: '2-digit',
          month: '2-digit',
          year: 'numeric'
        })}
        cost={subscriptionService.formatPrice(usageSummary.monthly_price)}
        onUpgrade={() => setShowPlans(true)}
        onManagePayment={() => setPaymentMethodModalOpen(true)}
        showUpgradeButton={usageSummary.plan !== 'enterprise'}
        isTrial={usageSummary.status === 'trialing' || isPilotSubscription}
        isPilot={isPilotSubscription}
        trialEndsAt={usageSummary.trial_ends_at ? new Date(usageSummary.trial_ends_at).toLocaleDateString('es-ES', {
          day: '2-digit',
          month: '2-digit',
          year: 'numeric'
        }) : undefined}
        trialDaysRemaining={usageSummary.trial_ends_at ? Math.max(0, Math.ceil((new Date(usageSummary.trial_ends_at).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))) : undefined}
      />

      {/* NEW: Critical Alerts Section - Only shown when needed */}
      {hasHighUsageMetrics && (
        <Card className="p-6 bg-gradient-to-r from-yellow-50 to-orange-50 dark:from-yellow-900/20 dark:to-orange-900/20 border-2 border-yellow-200 dark:border-yellow-700">
          <div className="flex items-start gap-4">
            <div className="w-12 h-12 rounded-full bg-gradient-to-br from-yellow-600 to-orange-600 flex items-center justify-center flex-shrink-0">
              <AlertTriangle className="w-6 h-6 text-white" />
            </div>
            <div className="flex-1">
              <h3 className="text-lg font-bold mb-2 text-yellow-800 dark:text-yellow-200">
                ¡Atención! Límite de uso cercano
              </h3>
              <p className="text-sm text-yellow-700 dark:text-yellow-300 mb-4">
                Estás acercándote a los límites de tu plan actual. Considera actualizar para evitar interrupciones.
              </p>
              <div className="flex flex-wrap gap-2">
                <Button
                  onClick={() => setShowUsage(true)}
                  variant="warning"
                >
                  <Info className="w-4 h-4 mr-2" />
                  Ver Detalles de Uso
                </Button>
                <Button
                  onClick={() => setShowPlans(true)}
                  variant="primary"
                >
                  <ArrowRight className="w-4 h-4 mr-2" />
                  Actualizar Plan
                </Button>
              </div>
            </div>
          </div>
        </Card>
      )}

      {/* NEW: Collapsible Usage Section */}
      <CollapsibleSection
        title="Uso de Recursos"
        icon={<TrendingUp className="w-5 h-5 text-orange-500" />}
        isOpen={showUsage}
        onToggle={() => setShowUsage(!showUsage)}
        showAlert={hasHighUsageMetrics}
      >

        {/* Spacing between content blocks */}
        <div className="h-6"></div>

        <div className="space-y-6">
          {/* Team & Organization */}
          <div>
            <h4 className="text-sm font-semibold text-[var(--text-secondary)] mb-4 uppercase tracking-wide flex items-center gap-2">
              <Users className="w-4 h-4" />
              Equipo & Organización
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <SimpleMetricCard
                icon={<Users className="w-5 h-5 text-blue-500" />}
                label="Usuarios Activos"
                value={formatLimitDisplay(
                  usageSummary.usage.users.current,
                  usageSummary.usage.users.limit,
                  "Ilimitado"
                )}
                status={getMetricStatus(usageSummary.usage.users.usage_percentage)}
              />
              <SimpleMetricCard
                icon={<MapPin className="w-5 h-5 text-green-500" />}
                label="Ubicaciones"
                value={formatLimitDisplay(
                  usageSummary.usage.locations.current,
                  usageSummary.usage.locations.limit,
                  "Ilimitado"
                )}
                status={getMetricStatus(usageSummary.usage.locations.usage_percentage)}
              />
            </div>
          </div>

          {/* Products & Inventory */}
          <div>
            <h4 className="text-sm font-semibold text-[var(--text-secondary)] mb-4 uppercase tracking-wide flex items-center gap-2">
              <Package className="w-4 h-4" />
              Productos & Inventario
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <SimpleMetricCard
                icon={<Package className="w-5 h-5 text-purple-500" />}
                label="Productos"
                value={formatLimitDisplay(
                  usageSummary.usage.products.current,
                  usageSummary.usage.products.limit,
                  "Ilimitado"
                )}
                status={getMetricStatus(usageSummary.usage.products.usage_percentage)}
              />
              <SimpleMetricCard
                icon={<ChefHat className="w-5 h-5 text-amber-500" />}
                label="Recetas"
                value={formatLimitDisplay(
                  usageSummary.usage.recipes.current,
                  usageSummary.usage.recipes.limit,
                  "Ilimitado"
                )}
                status={getMetricStatus(usageSummary.usage.recipes.usage_percentage)}
              />
              <SimpleMetricCard
                icon={<ShoppingCart className="w-5 h-5 text-teal-500" />}
                label="Proveedores"
                value={formatLimitDisplay(
                  usageSummary.usage.suppliers.current,
                  usageSummary.usage.suppliers.limit,
                  "Ilimitado"
                )}
                status={getMetricStatus(usageSummary.usage.suppliers.usage_percentage)}
              />
            </div>
          </div>

          {/* AI & Analytics */}
          <div>
            <h4 className="text-sm font-semibold text-[var(--text-secondary)] mb-4 uppercase tracking-wide flex items-center gap-2">
              <Sparkles className="w-4 h-4" />
              IA & Analíticas
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <SimpleMetricCard
                icon={<Database className="w-5 h-5 text-indigo-500" />}
                label="Predicciones de Demanda Hoy"
                value={formatLimitDisplay(
                  usageSummary.usage.training_jobs_today.current,
                  usageSummary.usage.training_jobs_today.limit,
                  "Ilimitado"
                )}
                status={getMetricStatus(usageSummary.usage.training_jobs_today.usage_percentage)}
              />
              <SimpleMetricCard
                icon={<TrendingUp className="w-5 h-5 text-pink-500" />}
                label="Reportes de Ventas Hoy"
                value={formatLimitDisplay(
                  usageSummary.usage.forecasts_today.current,
                  usageSummary.usage.forecasts_today.limit,
                  "Ilimitado"
                )}
                status={getMetricStatus(usageSummary.usage.forecasts_today.usage_percentage)}
              />
            </div>
          </div>

          {/* API & Storage */}
          <div>
            <h4 className="text-sm font-semibold text-[var(--text-secondary)] mb-4 uppercase tracking-wide flex items-center gap-2">
              <Zap className="w-4 h-4" />
              API & Almacenamiento
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <SimpleMetricCard
                icon={<Zap className="w-5 h-5 text-orange-500" />}
                label="Llamadas API (Esta Hora)"
                value={formatLimitDisplay(
                  usageSummary.usage.api_calls_this_hour.current,
                  usageSummary.usage.api_calls_this_hour.limit,
                  "Ilimitado"
                )}
                status={getMetricStatus(usageSummary.usage.api_calls_this_hour.usage_percentage)}
              />
              <SimpleMetricCard
                icon={<HardDrive className="w-5 h-5 text-cyan-500" />}
                label="Almacenamiento"
                value={`${usageSummary.usage.file_storage_used_gb.current.toFixed(2)} GB / ${usageSummary.usage.file_storage_used_gb.limit} GB`}
                status={getMetricStatus(usageSummary.usage.file_storage_used_gb.usage_percentage)}
              />
            </div>
          </div>

          {/* Detailed Usage Alerts - Only for high usage metrics */}
          {hasHighUsageMetrics && forecastUsage && (
            <div className="pt-6 border-t border-[var(--border-primary)]">
              <h4 className="text-sm font-semibold text-[var(--text-secondary)] mb-4 uppercase tracking-wide flex items-center gap-2">
                <AlertTriangle className="w-4 h-4 text-yellow-500" />
                Alertas de Uso
              </h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {forecastUsage.highUsageMetrics.map((metric: any) => (
                  <UsageAlertCard
                    key={metric.metric}
                    metric={metric.label || metric.metric}
                    current={metric.current}
                    limit={metric.limit}
                    percentage={metric.usage_percentage}
                    daysUntilLimit={metric.days_until_breach}
                    onUpgrade={() => handleUpgradeClick('professional', 'usage_alert')}
                    icon={metric.icon || <Package className="w-5 h-5" />}
                  />
                ))}
              </div>
            </div>
          )}
        </div>
      </CollapsibleSection>

      {/* NEW: Collapsible Billing Section */}
      <CollapsibleSection
        title="Facturación e Historial"
        icon={<Download className="w-5 h-5 text-blue-500" />}
        isOpen={showBilling}
        onToggle={() => setShowBilling(!showBilling)}
      >

        {/* Spacing between content blocks */}
        <div className="h-6"></div>

        <div className="space-y-6">
          {/* Payment Method */}
          <div className="p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-secondary)]">
            <div className="flex items-start gap-4">
              <div className="p-3 bg-blue-500/10 rounded-lg border border-blue-500/20 flex-shrink-0">
                <CreditCard className="w-6 h-6 text-blue-500" />
              </div>
              <div className="flex-1">
                <h4 className="font-semibold text-[var(--text-primary)] mb-2">Método de Pago</h4>
                <p className="text-sm text-[var(--text-secondary)] mb-4 leading-relaxed">
                  {currentPaymentMethod 
                    ? `Tarjeta terminada en ${currentPaymentMethod.last4} (${currentPaymentMethod.brand})`
                    : 'No hay método de pago configurado'}
                </p>
                <Button
                  variant="outline"
                  className="flex items-center gap-2"
                  onClick={() => setPaymentMethodModalOpen(true)}
                >
                  <CreditCard className="w-4 h-4" />
                  {currentPaymentMethod ? 'Actualizar Método de Pago' : 'Agregar Método de Pago'}
                </Button>
              </div>
            </div>
          </div>

          {/* Invoices */}
          <div>
            <h4 className="text-sm font-semibold text-[var(--text-secondary)] mb-4 uppercase tracking-wide">
              Historial de Facturas
            </h4>

            {invoicesLoading && !invoicesLoaded ? (
              <div className="flex items-center justify-center py-8">
                <div className="flex flex-col items-center gap-4">
                  <RefreshCw className="w-8 h-8 animate-spin text-[var(--color-primary)]" />
                  <p className="text-[var(--text-secondary)]">Cargando facturas...</p>
                </div>
              </div>
            ) : (!Array.isArray(invoices) || invoices.length === 0) ? (
              <div className="text-center py-8">
                <div className="flex flex-col items-center gap-3">
                  <div className="p-4 bg-[var(--bg-secondary)] rounded-full">
                    <Download className="w-8 h-8 text-[var(--text-tertiary)]" />
                  </div>
                  {(usageSummary?.status === 'trialing' || 
                   (usageSummary?.trial_ends_at && new Date(usageSummary.trial_ends_at) > new Date())) ? (
                    <>
                      <p className="text-[var(--text-secondary)]">Periodo de prueba activo</p>
                      <p className="text-sm text-[var(--text-tertiary)]">
                        No hay facturas durante el periodo de prueba. Las facturas aparecerán aquí 
                        una vez finalice el periodo de prueba el {usageSummary?.trial_ends_at ? new Date(usageSummary.trial_ends_at).toLocaleDateString('es-ES') : 'próximamente'}.
                      </p>
                    </>
                  ) : (
                    <>
                      <p className="text-[var(--text-secondary)]">No hay facturas disponibles</p>
                      <p className="text-sm text-[var(--text-tertiary)]">Las facturas aparecerán aquí una vez realizados los pagos</p>
                    </>
                  )}
                </div>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b border-[var(--border-color)]">
                      <th className="text-left py-3 px-4 text-[var(--text-secondary)] font-medium text-sm">Fecha</th>
                      <th className="text-left py-3 px-4 text-[var(--text-secondary)] font-medium text-sm">Descripción</th>
                      <th className="text-right py-3 px-4 text-[var(--text-secondary)] font-medium text-sm">Monto</th>
                      <th className="text-center py-3 px-4 text-[var(--text-secondary)] font-medium text-sm">Estado</th>
                      <th className="text-center py-3 px-4 text-[var(--text-secondary)] font-medium text-sm">Acciones</th>
                    </tr>
                  </thead>
                  <tbody>
                    {Array.isArray(invoices) && invoices.slice(0, 5).map((invoice) => (
                      <tr key={invoice.id} className="border-b border-[var(--border-color)] hover:bg-[var(--bg-secondary)] transition-colors">
                        <td className="py-3 px-4 text-[var(--text-primary)] font-medium">
                          {invoice.created ? new Date(invoice.created * 1000).toLocaleDateString('es-ES', {
                            day: '2-digit',
                            month: 'short',
                            year: 'numeric'
                          }) : 'N/A'}
                        </td>
                        <td className="py-3 px-4 text-[var(--text-primary)]">
                          {invoice.trial ? (
                            <span className="flex items-center gap-1">
                              <span className="text-green-500">●</span>
                              Periodo de prueba
                            </span>
                          ) : (invoice.description || 'Suscripción')}
                        </td>
                        <td className="py-3 px-4 text-[var(--text-primary)] font-semibold text-right">
                          {invoice.amount_due !== undefined ? (
                            invoice.trial ? (
                              <span className="text-green-500">0,00 €</span>
                            ) : (
                              subscriptionService.formatPrice(invoice.amount_due)
                            )
                          ) : 'N/A'}
                        </td>
                        <td className="py-3 px-4 text-center">
                          <Badge variant={invoice.trial ? 'success' : invoice.status === 'paid' ? 'success' : invoice.status === 'open' ? 'warning' : 'default'}>
                            {invoice.trial ? 'Prueba' : invoice.status === 'paid' ? 'Pagada' : invoice.status === 'open' ? 'Pendiente' : invoice.status}
                          </Badge>
                        </td>
                        <td className="py-3 px-4 text-center">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleDownloadInvoice(invoice)}
                            disabled={!invoice.invoice_pdf && !invoice.hosted_invoice_url}
                            className="flex items-center gap-2 mx-auto"
                          >
                            <Download className="w-4 h-4" />
                            {invoice.invoice_pdf ? 'PDF' : invoice.hosted_invoice_url ? 'Ver' : 'Descargar'}
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                {Array.isArray(invoices) && invoices.length > 5 && (
                  <div className="mt-4 text-center">
                    <Button variant="ghost" onClick={() => setShowBilling(true)}>
                      Ver todas las facturas ({invoices.length})
                    </Button>
                  </div>
                )}
              </div>
            )}
          </div>


        </div>
      </CollapsibleSection>

      {/* NEW: Collapsible Plans Section */}
      <CollapsibleSection
        title="Gestionar Suscripción"
        icon={<Settings className="w-5 h-5 text-purple-500" />}
        isOpen={showPlans}
        onToggle={() => setShowPlans(!showPlans)}
      >

        {/* Spacing between content blocks */}
        <div className="h-6"></div>

        <div className="space-y-6">
          {/* Available Plans */}
          <div>
            <h4 className="text-sm font-semibold text-[var(--text-secondary)] mb-4 uppercase tracking-wide">
              Planes Disponibles
            </h4>
            <SubscriptionPricingCards
              mode="settings"
              selectedPlan={usageSummary.plan}
              onPlanSelect={(plan) => handleUpgradeClick(plan, 'pricing_cards')}
              showPilotBanner={false}
            />
          </div>

          {/* Plan Comparison */}
          {availablePlans && (
            <div>
              <div className="flex items-center justify-between mb-4">
                <h4 className="text-sm font-semibold text-[var(--text-secondary)] uppercase tracking-wide">
                  Comparación Detallada
                </h4>
                <button
                  onClick={() => setShowComparison(!showComparison)}
                  className="text-sm text-[var(--color-primary)] hover:underline flex items-center gap-1"
                >
                  {showComparison ? (
                    <>
                      <ChevronUp className="w-4 h-4" />
                      Ocultar
                    </>
                  ) : (
                    <>
                      <ChevronDown className="w-4 h-4" />
                      Mostrar
                    </>
                  )}
                </button>
              </div>

              {showComparison && (
                <PlanComparisonTable
                  plans={availablePlans}
                  currentTier={usageSummary.plan}
                  onSelectPlan={(tier) => handleUpgradeClick(tier, 'comparison_table')}
                  mode="inline"
                />
              )}
            </div>
          )}

          {/* ROI Calculator for Starter tier */}
          {usageSummary.plan === 'starter' && (
            <div>
              <div className="flex items-center justify-between mb-4">
                <h4 className="text-sm font-semibold text-[var(--text-secondary)] uppercase tracking-wide">
                  Calcula Tus Ahorros
                </h4>
                <button
                  onClick={() => setShowROI(!showROI)}
                  className="text-sm text-[var(--color-primary)] hover:underline flex items-center gap-1"
                >
                  {showROI ? (
                    <>
                      <ChevronUp className="w-4 h-4" />
                      Ocultar
                    </>
                  ) : (
                    <>
                      <ChevronDown className="w-4 h-4" />
                      Mostrar
                    </>
                  )}
                </button>
              </div>

              {showROI && (
                <ROICalculator
                  currentTier="starter"
                  targetTier="professional"
                  monthlyPrice={149}
                  context="settings"
                  defaultExpanded={false}
                  onUpgrade={() => handleUpgradeClick('professional', 'roi_calculator')}
                />
              )}
            </div>
          )}

          {/* Cancel Subscription */}
          <div className="p-6 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-secondary)]">
            <div className="flex items-start gap-4">
              <div className="p-3 bg-red-500/10 rounded-lg border border-red-500/20 flex-shrink-0">
                <AlertCircle className="w-6 h-6 text-red-500" />
              </div>
              <div className="flex-1">
                <h4 className="font-semibold text-[var(--text-primary)] mb-2">Cancelar Suscripción</h4>
                <p className="text-sm text-[var(--text-secondary)] mb-4 leading-relaxed">
                  Si cancelas, mantendrás acceso de solo lectura hasta el final de tu período de facturación actual.
                </p>
                <Button
                  variant="danger"
                  onClick={handleCancellationClick}
                  className="flex items-center gap-2"
                >
                  <X className="w-4 h-4" />
                  Cancelar Suscripción
                </Button>
              </div>
            </div>
          </div>
        </div>
      </CollapsibleSection>

      {/* Payment Method Update Modal */}
      <PaymentMethodUpdateModal
        isOpen={paymentMethodModalOpen}
        onClose={() => setPaymentMethodModalOpen(false)}
        tenantId={currentTenant?.id || user?.tenant_id || ''}
        currentPaymentMethod={currentPaymentMethod}
        onPaymentMethodUpdated={(updatedMethod) => {
          setCurrentPaymentMethod(updatedMethod);
          showToast.success('Método de pago actualizado correctamente');
        }}
      />

      {/* Upgrade Dialog */}
      {upgradeDialogOpen && selectedPlan && availablePlans && (
        <DialogModal
          isOpen={upgradeDialogOpen}
          onClose={() => setUpgradeDialogOpen(false)}
          title="Confirmar Cambio de Plan"
          message={
            <div className="space-y-3">
              <p>¿Estás seguro de que quieres cambiar tu plan de suscripción?</p>
              {availablePlans.plans[selectedPlan as keyof typeof availablePlans.plans] && usageSummary && (
                <div className="p-4 bg-[var(--bg-secondary)] rounded-lg space-y-2">
                  <div className="flex justify-between">
                    <span>Plan actual:</span>
                    <span>{t(`plans.${usageSummary.plan}.name`, usageSummary.plan)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Nuevo plan:</span>
                    <span>{t(`plans.${selectedPlan}.name`, availablePlans.plans[selectedPlan as keyof typeof availablePlans.plans].name)}</span>
                  </div>
                  <div className="flex justify-between font-medium">
                    <span>Nuevo precio:</span>
                    <span>{subscriptionService.formatPrice(availablePlans.plans[selectedPlan as keyof typeof availablePlans.plans].monthly_price)}/mes</span>
                  </div>
                </div>
              )}
            </div>
          }
          type="confirm"
          onConfirm={handleUpgradeConfirm}
          onCancel={() => setUpgradeDialogOpen(false)}
          confirmLabel="Confirmar Cambio"
          cancelLabel="Cancelar"
          loading={upgrading}
        />
      )}

      {/* Cancellation Dialog */}
      {cancellationDialogOpen && (
        <DialogModal
          isOpen={cancellationDialogOpen}
          onClose={() => setCancellationDialogOpen(false)}
          title="Cancelar Suscripción"
          message={
            <div className="space-y-3">
              <p>¿Estás seguro de que deseas cancelar tu suscripción? Esta acción no se puede deshacer.</p>
              <p>Perderás acceso a las funcionalidades premium al final del período de facturación actual.</p>
            </div>
          }
          type="warning"
          onConfirm={handleCancelSubscription}
          onCancel={() => setCancellationDialogOpen(false)}
          confirmLabel="Confirmar Cancelación"
          cancelLabel="Volver"
          loading={cancelling}
        />
      )}
    </div>
  );
};

export default SubscriptionPageRedesign;