/**
 * Plans & Billing Page - Unified Subscription & Payment Management
 * Comprehensive dashboard for all billing-related features
 * Rich, actionable, data-driven UX following UsageDashboard patterns
 */

import { useState, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';
import {
  CreditCardIcon,
  TrendingUpIcon,
  FileTextIcon,
  WalletIcon,
  ArrowUpIcon,
  Loader2Icon,
  AlertCircleIcon,
  CheckCircleIcon,
  DownloadIcon,
  ZapIcon,
  GlobeIcon,
  UsersIcon,
  XIcon,
  CalendarIcon,
  RefreshCwIcon,
  ChevronRightIcon,
  PlusIcon,
  Building2Icon,
  TagIcon,
  LockIcon,
  ShootingStarIcon,
} from '../../icons';
import { Card } from '../../components/ui/card';
import Badge from '../../components/ui/badge/Badge';
import Button from '../../components/ui/button/Button';
import PageMeta from '../../components/common/PageMeta';
import PageHeader from '../../components/common/PageHeader';
import { useToast } from '../../components/ui/toast/ToastContainer';
import { usePageLoading } from '../../context/PageLoadingContext';
import { formatCurrency } from '../../utils';
import {
  getCreditBalance,
  getCreditPackages,
  getInvoices,
  getAvailablePaymentMethods,
  purchaseCreditPackage,
  downloadInvoicePDF,
  getPayments,
  type CreditBalance,
  type CreditPackage,
  type Invoice,
  type PaymentMethod,
  type Payment,
  getPlans,
  getSubscriptions,
  createSubscription,
  cancelSubscription,
  type Plan,
  type Subscription,
  // Payment gateway methods
  subscribeToPlan,
  purchaseCredits,
  openStripeBillingPortal,
  getAvailablePaymentGateways,
  type PaymentGateway,
} from '../../services/billing.api';
import { useAuthStore } from '../../store/authStore';

export default function PlansAndBillingPage() {
  const { startLoading, stopLoading } = usePageLoading();
  const toast = useToast();
  const hasLoaded = useRef(false);
  const { user } = useAuthStore.getState();
  const isAwsAdmin = user?.account?.slug === 'aws-admin';

  // UI States
  const [error, setError] = useState<string>('');
  const [planLoadingId, setPlanLoadingId] = useState<number | null>(null);
  const [purchaseLoadingId, setPurchaseLoadingId] = useState<number | null>(null);
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);
  const [showUpgradeModal, setShowUpgradeModal] = useState(false);
  const [selectedBillingCycle, setSelectedBillingCycle] = useState<'monthly' | 'annual'>('monthly');
  const [selectedGateway, setSelectedGateway] = useState<PaymentGateway>('stripe');

  // Data States
  const [creditBalance, setCreditBalance] = useState<CreditBalance | null>(null);
  const [packages, setPackages] = useState<CreditPackage[]>([]);
  const [invoices, setInvoices] = useState<Invoice[]>([]);
  const [payments, setPayments] = useState<Payment[]>([]);
  const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>([]);
  const [plans, setPlans] = useState<Plan[]>([]);
  const [subscriptions, setSubscriptions] = useState<Subscription[]>([]);
  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string | undefined>(undefined);
  const [availableGateways, setAvailableGateways] = useState<{ stripe: boolean; paypal: boolean; manual: boolean }>({
    stripe: false,
    paypal: false,
    manual: true,
  });

  useEffect(() => {
    if (hasLoaded.current) return;
    hasLoaded.current = true;
    loadData();

    // Handle payment gateway return URLs
    const params = new URLSearchParams(window.location.search);
    const success = params.get('success');
    const canceled = params.get('canceled');
    const purchase = params.get('purchase');

    if (success === 'true') {
      toast?.success?.('Subscription activated successfully!');
      // Clean up URL
      window.history.replaceState({}, '', window.location.pathname);
    } else if (canceled === 'true') {
      toast?.info?.('Payment was cancelled');
      window.history.replaceState({}, '', window.location.pathname);
    } else if (purchase === 'success') {
      toast?.success?.('Credits purchased successfully!');
      window.history.replaceState({}, '', window.location.pathname);
    } else if (purchase === 'canceled') {
      toast?.info?.('Credit purchase was cancelled');
      window.history.replaceState({}, '', window.location.pathname);
    }
  }, []);

  const handleError = (err: any, fallback: string) => {
    const message = err?.message || fallback;
    setError(message);
    toast?.error?.(message);
  };

  const loadData = async (allowRetry = true) => {
    try {
      startLoading('Loading billing data...');
      const wait = (ms: number) => new Promise((res) => setTimeout(res, ms));

      const balanceData = await getCreditBalance();
      const packagesPromise = getCreditPackages();
      const invoicesPromise = getInvoices({});
      const paymentsPromise = getPayments({});
      const methodsPromise = getAvailablePaymentMethods();
      const plansData = await getPlans();
      await wait(400);

      let subsData: { results: Subscription[] } = { results: [] };
      try {
        subsData = await getSubscriptions();
      } catch (subErr: any) {
        if (subErr?.status === 429 && allowRetry) {
          await wait(2500);
          try { subsData = await getSubscriptions(); } catch { subsData = { results: [] }; }
        }
      }

      const [packagesData, invoicesData, paymentsData, methodsData] = await Promise.all([
        packagesPromise, invoicesPromise, paymentsPromise, methodsPromise
      ]);

      setCreditBalance(balanceData);
      setPackages(packagesData.results || []);
      setInvoices(invoicesData.results || []);
      setPayments(paymentsData.results || []);

      const methods = (methodsData.results || []).filter((m) => m.is_enabled !== false);
      setPaymentMethods(methods);
      if (methods.length > 0) {
        const bank = methods.find((m) => m.type === 'bank_transfer');
        const manual = methods.find((m) => m.type === 'manual');
        const selected = bank || manual || methods.find((m) => m.is_default) || methods[0];
        setSelectedPaymentMethod((prev) => prev || selected.type || selected.id);
      }

      // Filter plans
      const activePlans = (plansData.results || []).filter((p) => p.is_active !== false);
      const filteredPlans = activePlans.filter((p) => {
        const name = (p.name || '').toLowerCase();
        const slug = (p.slug || '').toLowerCase();
        const isEnterprise = name.includes('enterprise') || slug === 'enterprise';
        return isAwsAdmin ? true : !isEnterprise;
      });

      const accountPlan = user?.account?.plan;
      if (accountPlan && !filteredPlans.find((p) => p.id === accountPlan.id)) {
        filteredPlans.push(accountPlan as any);
      }
      setPlans(filteredPlans);

      const subs = subsData.results || [];
      if (subs.length === 0 && accountPlan) {
        subs.push({ id: accountPlan.id || 0, plan: accountPlan, status: 'active' } as any);
      }
      setSubscriptions(subs);

      // Load available payment gateways
      try {
        const gateways = await getAvailablePaymentGateways();
        setAvailableGateways(gateways);
        // Auto-select first available gateway
        if (gateways.stripe) {
          setSelectedGateway('stripe');
        } else if (gateways.paypal) {
          setSelectedGateway('paypal');
        } else {
          setSelectedGateway('manual');
        }
      } catch {
        // Non-critical - just keep defaults
        console.log('Could not load payment gateways, using defaults');
      }
    } catch (err: any) {
      if (err?.status === 429 && allowRetry) {
        setError('Request was throttled. Retrying...');
        setTimeout(() => loadData(false), 2500);
      } else if (err?.status !== 429) {
        setError(err.message || 'Failed to load billing data');
      }
    } finally {
      stopLoading();
    }
  };

  const handleSelectPlan = async (planId: number) => {
    try {
      setPlanLoadingId(planId);

      // Use payment gateway integration for Stripe/PayPal
      if (selectedGateway === 'stripe' || selectedGateway === 'paypal') {
        const { redirect_url } = await subscribeToPlan(planId.toString(), selectedGateway);
        window.location.href = redirect_url;
        return;
      }

      // Fall back to manual/bank transfer flow
      await createSubscription({ plan_id: planId, payment_method: selectedPaymentMethod });
      toast?.success?.('Plan upgraded successfully!');
      setShowUpgradeModal(false);
      await loadData();
    } catch (err: any) {
      handleError(err, 'Failed to upgrade plan');
    } finally {
      setPlanLoadingId(null);
    }
  };

  const handleCancelSubscription = async () => {
    if (!currentSubscription?.id) return;
    try {
      setPlanLoadingId(currentSubscription.id);
      await cancelSubscription(currentSubscription.id);
      toast?.success?.('Subscription cancelled');
      setShowCancelConfirm(false);
      await loadData();
    } catch (err: any) {
      handleError(err, 'Failed to cancel subscription');
    } finally {
      setPlanLoadingId(null);
    }
  };

  const handlePurchaseCredits = async (packageId: number) => {
    try {
      setPurchaseLoadingId(packageId);

      // Use payment gateway integration for Stripe/PayPal
      if (selectedGateway === 'stripe' || selectedGateway === 'paypal') {
        const { redirect_url } = await purchaseCredits(packageId.toString(), selectedGateway);
        window.location.href = redirect_url;
        return;
      }

      // Fall back to manual/bank transfer flow
      await purchaseCreditPackage({ package_id: packageId, payment_method: selectedPaymentMethod as any || 'manual' });
      toast?.success?.('Credits purchased successfully!');
      await loadData();
    } catch (err: any) {
      handleError(err, 'Failed to purchase credits');
    } finally {
      setPurchaseLoadingId(null);
    }
  };

  const handleManageSubscription = async () => {
    try {
      const { portal_url } = await openStripeBillingPortal();
      window.location.href = portal_url;
    } catch (err: any) {
      handleError(err, 'Failed to open billing portal');
    }
  };

  const handleDownloadInvoice = async (invoiceId: number) => {
    try {
      const blob = await downloadInvoicePDF(invoiceId);
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `invoice-${invoiceId}.pdf`;
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
    } catch (err: any) {
      handleError(err, 'Failed to download invoice');
    }
  };

  // Computed values
  const currentSubscription = subscriptions.find((sub) => sub.status === 'active') || subscriptions[0];
  const currentPlanId = typeof currentSubscription?.plan === 'object' ? currentSubscription.plan.id : currentSubscription?.plan;
  const accountPlanId = user?.account?.plan?.id;
  const effectivePlanId = currentPlanId || accountPlanId;
  const currentPlan = plans.find((p) => p.id === effectivePlanId) || user?.account?.plan;
  const hasActivePlan = Boolean(effectivePlanId);
  const hasPendingPayment = payments.some((p) => p.status === 'pending_approval');

  // Credit usage percentage
  const creditUsage = creditBalance && creditBalance.plan_credits_per_month > 0
    ? Math.round((creditBalance.credits_used_this_month / creditBalance.plan_credits_per_month) * 100)
    : 0;

  // Upgrade plans (exclude current and free)
  const upgradePlans = plans.filter(p => {
    const price = Number(p.price) || 0;
    return price > 0 && p.id !== effectivePlanId;
  }).sort((a, b) => (Number(a.price) || 0) - (Number(b.price) || 0));

  return (
    <>
      <PageMeta title="Plans & Billing" description="Manage your subscription and payments" />
      <PageHeader
        title="Plans & Billing"
        description="Manage your subscription, credits, and payment history"
        badge={{ icon: <CreditCardIcon className="w-4 h-4" />, color: 'blue' }}
        actions={
          <Button
            size="sm"
            variant="outline"
            tone="neutral"
            onClick={() => loadData()}
            startIcon={<RefreshCwIcon className="w-4 h-4" />}
          >
            Refresh
          </Button>
        }
      />

      {/* Alerts */}
      {!hasActivePlan && (
        <div className="mb-6 p-4 rounded-xl border border-warning-200 bg-warning-50 dark:border-warning-800 dark:bg-warning-900/20 flex items-start gap-3">
          <AlertCircleIcon className="w-5 h-5 text-warning-600 dark:text-warning-400 mt-0.5 shrink-0" />
          <div>
            <p className="font-medium text-warning-800 dark:text-warning-200">No Active Plan</p>
            <p className="text-sm text-warning-700 dark:text-warning-300 mt-1">Choose a plan below to activate your account and unlock all features.</p>
          </div>
        </div>
      )}
      {hasPendingPayment && (
        <div className="mb-6 p-4 rounded-xl border border-info-200 bg-info-50 dark:border-info-800 dark:bg-info-900/20 flex items-start gap-3">
          <Loader2Icon className="w-5 h-5 text-info-600 dark:text-info-400 mt-0.5 shrink-0 animate-spin" />
          <div>
            <p className="font-medium text-info-800 dark:text-info-200">Payment Pending Review</p>
            <p className="text-sm text-info-700 dark:text-info-300 mt-1">Your payment is being processed. Credits will be added once approved.</p>
          </div>
        </div>
      )}
      {error && (
        <div className="mb-6 p-4 rounded-xl border border-error-200 bg-error-50 dark:border-error-800 dark:bg-error-900/20 flex items-start gap-3">
          <AlertCircleIcon className="w-5 h-5 text-error-600 dark:text-error-400 mt-0.5 shrink-0" />
          <p className="text-error-800 dark:text-error-200">{error}</p>
        </div>
      )}

      <div className="space-y-6">
        {/* SECTION 1: Current Plan Hero */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Main Plan Card */}
          <Card className="lg:col-span-2 p-6 bg-gradient-to-br from-brand-50 to-purple-50 dark:from-brand-900/20 dark:to-purple-900/20 border-0">
            <div className="flex items-start justify-between mb-6">
              <div>
                <div className="flex items-center gap-3 mb-2">
                  <h2 className="text-2xl font-bold text-gray-900 dark:text-white">
                    {currentPlan?.name || 'No Plan'}
                  </h2>
                  <Badge variant="soft" tone={hasActivePlan ? 'success' : 'warning'}>
                    {hasActivePlan ? 'Active' : 'Inactive'}
                  </Badge>
                </div>
                <p className="text-gray-600 dark:text-gray-400">
                  {currentPlan?.description || 'Select a plan to unlock features'}
                </p>
              </div>
              <div className="flex items-center gap-2">
                {availableGateways.stripe && hasActivePlan && (
                  <Button
                    variant="outline"
                    tone="neutral"
                    onClick={handleManageSubscription}
                    startIcon={<CreditCardIcon className="w-4 h-4" />}
                  >
                    Manage Billing
                  </Button>
                )}
                <Button
                  variant="primary"
                  tone="brand"
                  onClick={() => setShowUpgradeModal(true)}
                  startIcon={<ArrowUpIcon className="w-4 h-4" />}
                >
                  Upgrade
                </Button>
              </div>
            </div>

            {/* Quick Stats */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="p-4 bg-white/60 dark:bg-gray-800/40 rounded-xl">
                <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 mb-1">
                  <ZapIcon className="w-4 h-4 text-brand-500" />
                  Credits
                </div>
                <div className="text-2xl font-bold text-gray-900 dark:text-white">
                  {creditBalance?.credits?.toLocaleString() || 0}
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">Available now</div>
              </div>
              <div className="p-4 bg-white/60 dark:bg-gray-800/40 rounded-xl">
                <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 mb-1">
                  <TrendingUpIcon className="w-4 h-4 text-purple-500" />
                  Used
                </div>
                <div className="text-2xl font-bold text-gray-900 dark:text-white">
                  {creditBalance?.credits_used_this_month?.toLocaleString() || 0}
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">This month ({creditUsage}%)</div>
              </div>
              <div className="p-4 bg-white/60 dark:bg-gray-800/40 rounded-xl">
                <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 mb-1">
                  <CalendarIcon className="w-4 h-4 text-success-500" />
                  Renews
                </div>
                <div className="text-2xl font-bold text-gray-900 dark:text-white">
                  {currentSubscription?.current_period_end
                    ? new Date(currentSubscription.current_period_end).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
                    : '—'}
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">Next billing</div>
              </div>
              <div className="p-4 bg-white/60 dark:bg-gray-800/40 rounded-xl">
                <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 mb-1">
                  <WalletIcon className="w-4 h-4 text-warning-500" />
                  Monthly
                </div>
                <div className="text-2xl font-bold text-gray-900 dark:text-white">
                  ${Number(currentPlan?.price || 0).toFixed(0)}
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">Per month</div>
              </div>
            </div>

            {/* Credit Usage Bar */}
            <div className="mt-6 pt-6 border-t border-white/30 dark:border-gray-700/30">
              <div className="flex justify-between text-sm mb-2">
                <span className="text-gray-600 dark:text-gray-400">Credit Usage</span>
                <span className="font-medium text-gray-900 dark:text-white">
                  {creditBalance?.credits_used_this_month?.toLocaleString() || 0} / {creditBalance?.plan_credits_per_month?.toLocaleString() || 0}
                </span>
              </div>
              <div className="h-3 bg-white/50 dark:bg-gray-800/50 rounded-full overflow-hidden">
                <div
                  className={`h-full rounded-full transition-all duration-500 ${
                    creditUsage >= 90 ? 'bg-error-500' : creditUsage >= 70 ? 'bg-warning-500' : 'bg-gradient-to-r from-brand-500 to-purple-500'
                  }`}
                  style={{ width: `${Math.min(creditUsage, 100)}%` }}
                />
              </div>
            </div>
          </Card>

          {/* Plan Limits Summary */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold text-gray-900 dark:text-white">Plan Limits</h3>
              <Link to="/account/usage" className="text-sm text-brand-600 dark:text-brand-400 hover:underline flex items-center gap-1">
                View Usage <ChevronRightIcon className="w-4 h-4" />
              </Link>
            </div>
            <div className="space-y-4">
              <div className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-brand-100 dark:bg-brand-900/30 rounded-lg">
                    <GlobeIcon className="w-4 h-4 text-brand-600 dark:text-brand-400" />
                  </div>
                  <span className="text-sm text-gray-700 dark:text-gray-300">Sites</span>
                </div>
                <span className="font-bold text-gray-900 dark:text-white">
                  {currentPlan?.max_sites === 9999 ? '∞' : currentPlan?.max_sites || 0}
                </span>
              </div>
              <div className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-purple-100 dark:bg-purple-900/30 rounded-lg">
                    <UsersIcon className="w-4 h-4 text-purple-600 dark:text-purple-400" />
                  </div>
                  <span className="text-sm text-gray-700 dark:text-gray-300">Team Members</span>
                </div>
                <span className="font-bold text-gray-900 dark:text-white">
                  {currentPlan?.max_users === 9999 ? '∞' : currentPlan?.max_users || 0}
                </span>
              </div>
              <div className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-success-100 dark:bg-success-900/30 rounded-lg">
                    <TagIcon className="w-4 h-4 text-success-600 dark:text-success-400" />
                  </div>
                  <span className="text-sm text-gray-700 dark:text-gray-300">Keywords</span>
                </div>
                <span className="font-bold text-gray-900 dark:text-white">
                  {currentPlan?.max_keywords ? currentPlan.max_keywords.toLocaleString() : 0}
                </span>
              </div>
              <div className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-warning-100 dark:bg-warning-900/30 rounded-lg">
                    <ZapIcon className="w-4 h-4 text-warning-600 dark:text-warning-400" />
                  </div>
                  <span className="text-sm text-gray-700 dark:text-gray-300">Monthly Credits</span>
                </div>
                <span className="font-bold text-gray-900 dark:text-white">
                  {currentPlan?.included_credits?.toLocaleString() || 0}
                </span>
              </div>
            </div>

            {hasActivePlan && (
              <button
                onClick={() => setShowCancelConfirm(true)}
                className="mt-4 w-full text-sm text-gray-500 dark:text-gray-400 hover:text-error-600 dark:hover:text-error-400 transition-colors"
              >
                Cancel Subscription
              </button>
            )}
          </Card>
        </div>

        {/* SECTION 2: Buy Credits + Quick Upgrade */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Buy Additional Credits */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-success-100 dark:bg-success-900/30 rounded-lg">
                  <PlusIcon className="w-5 h-5 text-success-600 dark:text-success-400" />
                </div>
                <div>
                  <h3 className="font-semibold text-gray-900 dark:text-white">Buy Credits</h3>
                  <p className="text-xs text-gray-500 dark:text-gray-400">Top up your credit balance</p>
                </div>
              </div>
              {/* Compact Payment Gateway Selector for Credits */}
              {(availableGateways.stripe || availableGateways.paypal) && (
                <div className="flex items-center gap-1 bg-gray-100 dark:bg-gray-800 p-1 rounded-lg">
                  {availableGateways.stripe && (
                    <button
                      onClick={() => setSelectedGateway('stripe')}
                      className={`p-1.5 rounded-md transition-colors ${
                        selectedGateway === 'stripe'
                          ? 'bg-white dark:bg-gray-700 shadow-sm'
                          : 'hover:bg-white/50 dark:hover:bg-gray-700/50'
                      }`}
                      title="Pay with Card"
                    >
                      <CreditCardIcon className={`w-4 h-4 ${selectedGateway === 'stripe' ? 'text-brand-600' : 'text-gray-500'}`} />
                    </button>
                  )}
                  {availableGateways.paypal && (
                    <button
                      onClick={() => setSelectedGateway('paypal')}
                      className={`p-1.5 rounded-md transition-colors ${
                        selectedGateway === 'paypal'
                          ? 'bg-white dark:bg-gray-700 shadow-sm'
                          : 'hover:bg-white/50 dark:hover:bg-gray-700/50'
                      }`}
                      title="Pay with PayPal"
                    >
                      <WalletIcon className={`w-4 h-4 ${selectedGateway === 'paypal' ? 'text-blue-600' : 'text-gray-500'}`} />
                    </button>
                  )}
                </div>
              )}
            </div>
            <div className="grid grid-cols-2 gap-3">
              {packages.slice(0, 4).map((pkg) => (
                <button
                  key={pkg.id}
                  onClick={() => handlePurchaseCredits(pkg.id)}
                  disabled={purchaseLoadingId === pkg.id}
                  className="p-4 border border-gray-200 dark:border-gray-700 rounded-xl hover:border-brand-500 dark:hover:border-brand-500 hover:bg-brand-50/50 dark:hover:bg-brand-900/20 transition-all text-left group"
                >
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-lg font-bold text-gray-900 dark:text-white">
                      {pkg.credits.toLocaleString()}
                    </span>
                  </div>
                  <div className="text-sm text-gray-500 dark:text-gray-400 mb-1">credits</div>
                  <div className="font-semibold text-brand-600 dark:text-brand-400 group-hover:text-brand-700 dark:group-hover:text-brand-300">
                    ${pkg.price}
                  </div>
                  {purchaseLoadingId === pkg.id && (
                    <Loader2Icon className="w-4 h-4 animate-spin mt-2" />
                  )}
                </button>
              ))}
            </div>
          </Card>

          {/* Quick Upgrade Options */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-purple-100 dark:bg-purple-900/30 rounded-lg">
                  <ShootingStarIcon className="w-5 h-5 text-purple-600 dark:text-purple-400" />
                </div>
                <div>
                  <h3 className="font-semibold text-gray-900 dark:text-white">Upgrade Plan</h3>
                  <p className="text-xs text-gray-500 dark:text-gray-400">Get more features & credits</p>
                </div>
              </div>
              <Button
                size="sm"
                variant="outline"
                tone="brand"
                onClick={() => setShowUpgradeModal(true)}
              >
                View All
              </Button>
            </div>
            <div className="space-y-3">
              {upgradePlans.slice(0, 3).map((plan) => (
                <div
                  key={plan.id}
                  className="p-4 border border-gray-200 dark:border-gray-700 rounded-xl flex items-center justify-between hover:border-purple-300 dark:hover:border-purple-700 transition-colors"
                >
                  <div>
                    <div className="font-semibold text-gray-900 dark:text-white">{plan.name}</div>
                    <div className="text-sm text-gray-500 dark:text-gray-400">
                      {plan.included_credits?.toLocaleString() || 0} credits/mo
                    </div>
                  </div>
                  <div className="text-right">
                    <div className="font-bold text-gray-900 dark:text-white">${plan.price}/mo</div>
                    <Button
                      size="sm"
                      variant="ghost"
                      tone="brand"
                      onClick={() => handleSelectPlan(plan.id)}
                      disabled={planLoadingId === plan.id}
                    >
                      {planLoadingId === plan.id ? <Loader2Icon className="w-4 h-4 animate-spin" /> : 'Select'}
                    </Button>
                  </div>
                </div>
              ))}
              {upgradePlans.length === 0 && (
                <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                  <CheckCircleIcon className="w-8 h-8 mx-auto mb-2 text-success-500" />
                  <p>You're on the best plan!</p>
                </div>
              )}
            </div>
          </Card>
        </div>

        {/* SECTION 3: Billing History */}
        <Card className="overflow-hidden">
          <div className="p-6 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-gray-100 dark:bg-gray-800 rounded-lg">
                <FileTextIcon className="w-5 h-5 text-gray-600 dark:text-gray-400" />
              </div>
              <div>
                <h3 className="font-semibold text-gray-900 dark:text-white">Billing History</h3>
                <p className="text-xs text-gray-500 dark:text-gray-400">Recent invoices and transactions</p>
              </div>
            </div>
          </div>
          <div className="overflow-x-auto">
            <table className="igny8-table-compact min-w-full w-full">
              <thead className="border-b border-gray-100 dark:border-white/[0.05]">
                <tr>
                  <th className="px-6 py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400">Invoice</th>
                  <th className="px-6 py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400">Date</th>
                  <th className="px-6 py-3 font-medium text-gray-500 text-center text-theme-xs dark:text-gray-400">Amount</th>
                  <th className="px-6 py-3 font-medium text-gray-500 text-center text-theme-xs dark:text-gray-400">Status</th>
                  <th className="px-6 py-3 font-medium text-gray-500 text-end text-theme-xs dark:text-gray-400">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100 dark:divide-white/[0.05]">
                {invoices.length === 0 ? (
                  <tr>
                    <td colSpan={5}>
                      <div className="text-center py-12">
                        <FileTextIcon className="w-10 h-10 mx-auto text-gray-300 dark:text-gray-600 mb-3" />
                        <h4 className="text-base font-medium text-gray-900 dark:text-white mb-1">No invoices yet</h4>
                        <p className="text-sm text-gray-500 dark:text-gray-400">Your billing history will appear here</p>
                      </div>
                    </td>
                  </tr>
                ) : (
                  invoices.slice(0, 5).map((invoice) => (
                    <tr key={invoice.id} className="igny8-data-row">
                      <td className="px-6 py-3 font-medium text-gray-900 dark:text-white">{invoice.invoice_number}</td>
                      <td className="px-6 py-3 text-gray-600 dark:text-gray-400">
                        {new Date(invoice.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                      </td>
                      <td className="px-6 py-3 text-center font-semibold text-gray-900 dark:text-white">{formatCurrency(invoice.total_amount, invoice.currency)}</td>
                      <td className="px-6 py-3 text-center">
                        <Badge variant="soft" tone={invoice.status === 'paid' ? 'success' : 'warning'}>
                          {invoice.status}
                        </Badge>
                      </td>
                      <td className="px-6 py-3 text-end">
                        <Button
                          size="sm"
                          variant="ghost"
                          tone="neutral"
                          startIcon={<DownloadIcon className="w-4 h-4" />}
                          onClick={() => handleDownloadInvoice(invoice.id)}
                        >
                          PDF
                        </Button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </Card>

        {/* SECTION 4: Payment Methods */}
        <Card className="p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-info-100 dark:bg-info-900/30 rounded-lg">
                <CreditCardIcon className="w-5 h-5 text-info-600 dark:text-info-400" />
              </div>
              <div>
                <h3 className="font-semibold text-gray-900 dark:text-white">Payment Methods</h3>
                <p className="text-xs text-gray-500 dark:text-gray-400">Manage how you pay</p>
              </div>
            </div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {paymentMethods.map((method) => (
              <div
                key={method.id}
                className={`p-4 border rounded-xl transition-all ${
                  selectedPaymentMethod === method.type
                    ? 'border-brand-500 bg-brand-50/50 dark:bg-brand-900/20'
                    : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
                }`}
              >
                <div className="flex items-start justify-between mb-3">
                  <div className="flex items-center gap-3">
                    {method.type === 'bank_transfer' ? (
                      <Building2Icon className="w-6 h-6 text-gray-500" />
                    ) : (
                      <CreditCardIcon className="w-6 h-6 text-gray-500" />
                    )}
                    <div>
                      <div className="font-medium text-gray-900 dark:text-white">{method.display_name}</div>
                      <div className="text-xs text-gray-500 dark:text-gray-400 capitalize">{method.type?.replace('_', ' ')}</div>
                    </div>
                  </div>
                  {method.is_default && (
                    <Badge variant="soft" tone="success" size="sm">Default</Badge>
                  )}
                </div>
                {selectedPaymentMethod !== method.type && (
                  <Button
                    size="sm"
                    variant="outline"
                    tone="neutral"
                    className="w-full"
                    onClick={() => setSelectedPaymentMethod(method.type)}
                  >
                    Select
                  </Button>
                )}
                {selectedPaymentMethod === method.type && (
                  <div className="flex items-center gap-2 text-sm text-brand-600 dark:text-brand-400">
                    <CheckCircleIcon className="w-4 h-4" />
                    Selected for payment
                  </div>
                )}
              </div>
            ))}
            {paymentMethods.length === 0 && (
              <div className="col-span-full text-center py-8 text-gray-500 dark:text-gray-400">
                No payment methods available
              </div>
            )}
          </div>
        </Card>
      </div>

      {/* Upgrade Modal */}
      {showUpgradeModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-auto">
            <div className="sticky top-0 bg-white dark:bg-gray-900 flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700 z-10">
              <div>
                <h2 className="text-xl font-bold text-gray-900 dark:text-white">Choose Your Plan</h2>
                <p className="text-sm text-gray-500 dark:text-gray-400">Select the plan that fits your needs</p>
              </div>
              <button
                onClick={() => setShowUpgradeModal(false)}
                className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
              >
                <XIcon className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            {/* Billing Toggle & Payment Gateway */}
            <div className="flex flex-col sm:flex-row items-center justify-center gap-4 py-6">
              {/* Billing Cycle Toggle */}
              <div className="bg-gray-100 dark:bg-gray-800 p-1 rounded-lg flex gap-1">
                <button
                  onClick={() => setSelectedBillingCycle('monthly')}
                  className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                    selectedBillingCycle === 'monthly'
                      ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
                      : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
                  }`}
                >
                  Monthly
                </button>
                <button
                  onClick={() => setSelectedBillingCycle('annual')}
                  className={`px-4 py-2 rounded-md text-sm font-medium transition-colors flex items-center gap-2 ${
                    selectedBillingCycle === 'annual'
                      ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
                      : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
                  }`}
                >
                  Annual
                  <Badge variant="soft" tone="success" size="sm">Save 20%</Badge>
                </button>
              </div>

              {/* Payment Gateway Selector */}
              {(availableGateways.stripe || availableGateways.paypal) && (
                <div className="bg-gray-100 dark:bg-gray-800 p-1 rounded-lg flex gap-1">
                  {availableGateways.stripe && (
                    <button
                      onClick={() => setSelectedGateway('stripe')}
                      className={`px-4 py-2 rounded-md text-sm font-medium transition-colors flex items-center gap-2 ${
                        selectedGateway === 'stripe'
                          ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
                          : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
                      }`}
                    >
                      <CreditCardIcon className="w-4 h-4" />
                      Card
                    </button>
                  )}
                  {availableGateways.paypal && (
                    <button
                      onClick={() => setSelectedGateway('paypal')}
                      className={`px-4 py-2 rounded-md text-sm font-medium transition-colors flex items-center gap-2 ${
                        selectedGateway === 'paypal'
                          ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
                          : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
                      }`}
                    >
                      <WalletIcon className="w-4 h-4" />
                      PayPal
                    </button>
                  )}
                  {availableGateways.manual && (
                    <button
                      onClick={() => setSelectedGateway('manual')}
                      className={`px-4 py-2 rounded-md text-sm font-medium transition-colors flex items-center gap-2 ${
                        selectedGateway === 'manual'
                          ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
                          : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
                      }`}
                    >
                      <Building2Icon className="w-4 h-4" />
                      Bank
                    </button>
                  )}
                </div>
              )}
            </div>

            {/* Plans Grid */}
            <div className="p-6 grid grid-cols-1 md:grid-cols-3 gap-4">
              {upgradePlans.map((plan, index) => {
                const isPopular = index === 1;
                const planPrice = Number(plan.price) || 0;
                const annualPrice = planPrice * 0.8 * 12;
                const displayPrice = selectedBillingCycle === 'annual' ? (annualPrice / 12).toFixed(0) : planPrice;
                
                return (
                  <div
                    key={plan.id}
                    className={`relative p-6 border rounded-2xl transition-all ${
                      isPopular
                        ? 'border-brand-500 bg-brand-50/50 dark:bg-brand-900/20 shadow-lg scale-105'
                        : 'border-gray-200 dark:border-gray-700 hover:border-brand-300 dark:hover:border-brand-700'
                    }`}
                  >
                    {isPopular && (
                      <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                        <Badge variant="solid" tone="brand">Most Popular</Badge>
                      </div>
                    )}
                    <div className="text-center mb-6">
                      <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-2">{plan.name}</h3>
                      <div className="flex items-baseline justify-center gap-1">
                        <span className="text-4xl font-bold text-gray-900 dark:text-white">${displayPrice}</span>
                        <span className="text-gray-500 dark:text-gray-400">/mo</span>
                      </div>
                      {selectedBillingCycle === 'annual' && (
                        <div className="text-sm text-success-600 dark:text-success-400 mt-1">
                          ${annualPrice.toFixed(0)} billed annually
                        </div>
                      )}
                    </div>
                    <ul className="space-y-3 mb-6">
                      <li className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                        <CheckCircleIcon className="w-4 h-4 text-success-500 shrink-0" />
                        {plan.included_credits?.toLocaleString() || 0} credits/month
                      </li>
                      <li className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                        <CheckCircleIcon className="w-4 h-4 text-success-500 shrink-0" />
                        {plan.max_sites === 9999 ? 'Unlimited' : plan.max_sites} sites
                      </li>
                      <li className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                        <CheckCircleIcon className="w-4 h-4 text-success-500 shrink-0" />
                        {plan.max_users === 9999 ? 'Unlimited' : plan.max_users} team members
                      </li>
                      <li className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                        <CheckCircleIcon className="w-4 h-4 text-success-500 shrink-0" />
                        {plan.max_keywords?.toLocaleString() || 0} keywords
                      </li>
                    </ul>
                    <Button
                      variant={isPopular ? 'primary' : 'outline'}
                      tone="brand"
                      className="w-full"
                      onClick={() => handleSelectPlan(plan.id)}
                      disabled={planLoadingId === plan.id}
                    >
                      {planLoadingId === plan.id ? (
                        <Loader2Icon className="w-4 h-4 animate-spin" />
                      ) : (
                        'Choose Plan'
                      )}
                    </Button>
                  </div>
                );
              })}
            </div>

            {/* Policy Info */}
            <div className="p-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 rounded-b-2xl">
              <div className="flex items-start gap-3">
                <LockIcon className="w-5 h-5 text-success-500 mt-0.5 shrink-0" />
                <div className="text-sm text-gray-600 dark:text-gray-400">
                  <strong className="text-gray-900 dark:text-white">Flexible billing:</strong> Upgrades take effect immediately with prorated billing. 
                  Downgrades apply at the end of your billing period. Cancel anytime with no penalties.
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Cancel Confirmation Modal */}
      {showCancelConfirm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-md">
            <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
              <h2 className="text-xl font-semibold text-gray-900 dark:text-white">Cancel Subscription</h2>
              <button
                onClick={() => setShowCancelConfirm(false)}
                className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              >
                <XIcon className="w-5 h-5 text-gray-500" />
              </button>
            </div>
            <div className="p-6 space-y-4">
              <div className="flex items-start gap-3 p-4 bg-warning-50 dark:bg-warning-900/20 border border-warning-200 dark:border-warning-800 rounded-lg">
                <AlertCircleIcon className="w-5 h-5 text-warning-600 dark:text-warning-400 mt-0.5 shrink-0" />
                <div className="text-sm text-warning-800 dark:text-warning-200">
                  <p className="font-medium mb-1">Are you sure?</p>
                  <p>Your subscription will remain active until the end of your billing period.</p>
                </div>
              </div>
              <ul className="text-sm text-gray-600 dark:text-gray-400 space-y-2 pl-2">
                <li className="flex items-start gap-2">
                  <span className="text-error-500 mt-1">•</span>
                  <span>You'll lose access to premium features</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-error-500 mt-1">•</span>
                  <span>Remaining credits preserved for 30 days</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-success-500 mt-1">•</span>
                  <span>Resubscribe anytime to restore access</span>
                </li>
              </ul>
            </div>
            <div className="flex items-center justify-end gap-3 p-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 rounded-b-xl">
              <Button variant="outline" tone="neutral" onClick={() => setShowCancelConfirm(false)}>
                Keep Subscription
              </Button>
              <Button
                variant="primary"
                tone="danger"
                onClick={handleCancelSubscription}
                disabled={planLoadingId === currentSubscription?.id}
              >
                {planLoadingId === currentSubscription?.id ? (
                  <><Loader2Icon className="w-4 h-4 mr-2 animate-spin" />Cancelling...</>
                ) : (
                  'Yes, Cancel'
                )}
              </Button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
