/**
 * Billing Settings Page
 *
 * Manage subscription plan, add-ons, payment methods, and view invoices.
 */

import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useOutletContext, useSearchParams } from 'react-router-dom';
import { useQuery, useMutation } from '@tanstack/react-query';
import {
  CreditCard, Crown, Plus, Trash2, Check, AlertCircle,
  FileText, ExternalLink, Wallet, Star, Loader2, Sparkles,
  ArrowRight, Package, Zap, X, RotateCcw, Calendar
} from 'lucide-react';
import { Business, User } from '../../types';
import {
  getSubscriptionPlans,
  createCheckoutSession,
  getSubscriptions,
  cancelSubscription,
  reactivateSubscription,
  SubscriptionPlan,
  ActiveSubscription,
} from '../../api/payments';

const BillingSettings: React.FC = () => {
  const { t } = useTranslation();
  const { business, user } = useOutletContext<{
    business: Business;
    user: User;
  }>();
  const [searchParams] = useSearchParams();

  const [showAddCard, setShowAddCard] = useState(false);
  const [showUpgradeModal, setShowUpgradeModal] = useState(false);
  const [selectedPlan, setSelectedPlan] = useState<SubscriptionPlan | null>(null);
  const [cancellingSubscription, setCancellingSubscription] = useState<ActiveSubscription | null>(null);
  const isOwner = user.role === 'owner';

  // Check for checkout success/cancel
  const checkoutStatus = searchParams.get('checkout');
  const [showCheckoutMessage, setShowCheckoutMessage] = useState(!!checkoutStatus);

  useEffect(() => {
    if (checkoutStatus) {
      // Clear the URL params after showing message
      const timer = setTimeout(() => {
        setShowCheckoutMessage(false);
        window.history.replaceState({}, '', '/settings/billing');
      }, 5000);
      return () => clearTimeout(timer);
    }
  }, [checkoutStatus]);

  // Fetch subscription plans
  const { data: plansData, isLoading: plansLoading } = useQuery({
    queryKey: ['subscriptionPlans'],
    queryFn: async () => {
      const response = await getSubscriptionPlans();
      return response.data;
    },
  });

  // Checkout mutation
  const checkoutMutation = useMutation({
    mutationFn: async (plan: SubscriptionPlan) => {
      const response = await createCheckoutSession(plan.id);
      return response.data;
    },
    onSuccess: (data) => {
      // Redirect to Stripe Checkout
      window.location.href = data.checkout_url;
    },
  });

  // Fetch active subscriptions
  const { data: subscriptionsData, isLoading: subscriptionsLoading, refetch: refetchSubscriptions } = useQuery({
    queryKey: ['subscriptions'],
    queryFn: async () => {
      const response = await getSubscriptions();
      return response.data;
    },
  });

  // Cancel subscription mutation
  const cancelMutation = useMutation({
    mutationFn: async ({ subscriptionId, immediate }: { subscriptionId: string; immediate: boolean }) => {
      const response = await cancelSubscription(subscriptionId, immediate);
      return response.data;
    },
    onSuccess: () => {
      setCancellingSubscription(null);
      refetchSubscriptions();
    },
  });

  // Reactivate subscription mutation
  const reactivateMutation = useMutation({
    mutationFn: async (subscriptionId: string) => {
      const response = await reactivateSubscription(subscriptionId);
      return response.data;
    },
    onSuccess: () => {
      refetchSubscriptions();
    },
  });

  // Mock payment methods - in a real app, these would come from Stripe
  const [paymentMethods] = useState([
    { id: 'pm_1', brand: 'visa', last4: '4242', expMonth: 12, expYear: 2025, isDefault: true },
  ]);

  const handleUpgrade = (plan: SubscriptionPlan) => {
    setSelectedPlan(plan);
    if (plan.stripe_price_id) {
      checkoutMutation.mutate(plan);
    } else {
      // Plan not configured for purchase yet
      alert('This plan is not available for purchase yet. Please contact support.');
    }
  };

  const formatPrice = (price: number | null) => {
    if (price === null) return 'Contact Us';
    return `$${price}/mo`;
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

  const activeSubscriptions = subscriptionsData?.subscriptions || [];

  if (!isOwner) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-500 dark:text-gray-400">
          Only the business owner can access these settings.
        </p>
      </div>
    );
  }

  const currentTier = plansData?.current_tier || business.plan || 'Free';
  const currentPlan = plansData?.current_plan;
  const availablePlans = plansData?.plans || [];
  const availableAddons = plansData?.addons || [];

  return (
    <div className="space-y-6">
      {/* Checkout Status Message */}
      {showCheckoutMessage && (
        <div className={`p-4 rounded-lg ${
          checkoutStatus === 'success'
            ? 'bg-green-50 border border-green-200 text-green-800'
            : 'bg-yellow-50 border border-yellow-200 text-yellow-800'
        }`}>
          {checkoutStatus === 'success' ? (
            <div className="flex items-center gap-2">
              <Check size={20} />
              <span>Your subscription has been updated! Changes may take a few minutes to apply.</span>
            </div>
          ) : (
            <div className="flex items-center gap-2">
              <AlertCircle size={20} />
              <span>Checkout was cancelled. No changes were made to your subscription.</span>
            </div>
          )}
        </div>
      )}

      {/* Header */}
      <div>
        <h2 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
          <CreditCard className="text-emerald-500" />
          {t('settings.billing.title', 'Plan & Billing')}
        </h2>
        <p className="text-gray-500 dark:text-gray-400 mt-1">
          Manage your subscription, add-ons, payment methods, and billing history.
        </p>
      </div>

      {/* Current Plan */}
      <section className="bg-white dark:bg-gray-800 p-6 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm">
        <div className="flex items-start justify-between">
          <div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
              <Crown size={20} className="text-amber-500" />
              Current Plan
            </h3>
            <div className="mt-4">
              <div className="flex items-baseline gap-2">
                <span className="text-3xl font-bold text-gray-900 dark:text-white">
                  {currentTier}
                </span>
                {currentPlan && (
                  <span className="text-gray-500 dark:text-gray-400">
                    {formatPrice(currentPlan.price_monthly)}
                  </span>
                )}
              </div>
              {currentPlan?.features && currentPlan.features.length > 0 && (
                <ul className="mt-4 space-y-2">
                  {currentPlan.features.slice(0, 5).map((feature, idx) => (
                    <li key={idx} className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
                      <Check size={16} className="text-green-500" />
                      {feature}
                    </li>
                  ))}
                </ul>
              )}
            </div>
          </div>
          <button
            onClick={() => setShowUpgradeModal(true)}
            className="px-4 py-2 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:from-indigo-600 hover:to-purple-600 transition-all flex items-center gap-2"
          >
            <Crown size={16} />
            {currentTier === 'Enterprise' ? 'Manage Plan' : 'Upgrade Plan'}
          </button>
        </div>
      </section>

      {/* Active Subscriptions */}
      <section className="bg-white dark:bg-gray-800 p-6 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2 mb-4">
          <Calendar size={20} className="text-blue-500" />
          Active Subscriptions
        </h3>

        {subscriptionsLoading ? (
          <div className="flex items-center justify-center py-8">
            <Loader2 className="animate-spin text-gray-400" size={24} />
          </div>
        ) : activeSubscriptions.length === 0 ? (
          <div className="text-center py-8 text-gray-500 dark:text-gray-400">
            <Calendar size={40} className="mx-auto mb-2 opacity-30" />
            <p>No active subscriptions.</p>
            <p className="text-sm mt-1">Subscribe to a plan to get started.</p>
          </div>
        ) : (
          <div className="space-y-4">
            {activeSubscriptions.map((subscription) => (
              <div
                key={subscription.id}
                className={`border rounded-lg p-4 ${
                  subscription.cancel_at_period_end
                    ? 'border-yellow-300 bg-yellow-50 dark:border-yellow-700 dark:bg-yellow-900/20'
                    : 'border-gray-200 dark:border-gray-700'
                }`}
              >
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-2">
                      <h4 className="font-medium text-gray-900 dark:text-white">
                        {subscription.plan_name}
                      </h4>
                      <span className={`px-2 py-0.5 text-xs font-medium rounded-full ${
                        subscription.plan_type === 'addon'
                          ? 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300'
                          : 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300'
                      }`}>
                        {subscription.plan_type === 'addon' ? 'Add-on' : 'Plan'}
                      </span>
                      {subscription.cancel_at_period_end && (
                        <span className="px-2 py-0.5 text-xs font-medium rounded-full bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300">
                          Cancelling
                        </span>
                      )}
                    </div>

                    <div className="mt-2 text-sm text-gray-600 dark:text-gray-400 space-y-1">
                      <p>
                        <span className="font-medium">{subscription.amount_display}</span>
                        <span className="text-gray-500">/{subscription.interval}</span>
                      </p>
                      <p>
                        {subscription.cancel_at_period_end ? (
                          <>Cancels on {formatDate(subscription.current_period_end)}</>
                        ) : (
                          <>Next billing: {formatDate(subscription.current_period_end)}</>
                        )}
                      </p>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    {subscription.cancel_at_period_end ? (
                      <button
                        onClick={() => reactivateMutation.mutate(subscription.stripe_subscription_id)}
                        disabled={reactivateMutation.isPending}
                        className="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-green-600 border border-green-600 rounded-lg hover:bg-green-50 dark:hover:bg-green-900/20 transition-colors disabled:opacity-50"
                      >
                        {reactivateMutation.isPending ? (
                          <Loader2 size={14} className="animate-spin" />
                        ) : (
                          <RotateCcw size={14} />
                        )}
                        Reactivate
                      </button>
                    ) : (
                      <button
                        onClick={() => setCancellingSubscription(subscription)}
                        className="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-red-600 border border-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
                      >
                        <X size={14} />
                        Cancel
                      </button>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </section>

      {/* Available Add-ons */}
      {availableAddons.length > 0 && (
        <section className="bg-white dark:bg-gray-800 p-6 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2 mb-4">
            <Package size={20} className="text-purple-500" />
            Available Add-ons
          </h3>
          <p className="text-sm text-gray-500 dark:text-gray-400 mb-4">
            Enhance your plan with additional features
          </p>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {availableAddons.map((addon) => (
              <div
                key={addon.id}
                className="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:border-purple-300 dark:hover:border-purple-700 transition-colors"
              >
                <div className="flex items-start justify-between mb-3">
                  <div>
                    <h4 className="font-medium text-gray-900 dark:text-white">{addon.name}</h4>
                    <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                      {addon.description || 'Enhance your subscription'}
                    </p>
                  </div>
                  <Sparkles size={20} className="text-purple-500" />
                </div>
                <div className="flex items-center justify-between mt-4">
                  <span className="text-lg font-semibold text-gray-900 dark:text-white">
                    {formatPrice(addon.price_monthly)}
                  </span>
                  <button
                    onClick={() => handleUpgrade(addon)}
                    disabled={checkoutMutation.isPending}
                    className="px-3 py-1.5 text-sm font-medium text-purple-600 border border-purple-600 rounded-lg hover:bg-purple-50 dark:hover:bg-purple-900/20 transition-colors disabled:opacity-50"
                  >
                    {checkoutMutation.isPending && selectedPlan?.id === addon.id ? (
                      <Loader2 size={16} className="animate-spin" />
                    ) : (
                      'Add'
                    )}
                  </button>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}

      {/* Wallet / Credits Summary */}
      <section className="bg-white dark:bg-gray-800 p-6 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2 mb-4">
          <Wallet size={20} className="text-blue-500" />
          Wallet
        </h3>
        <div className="bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 rounded-lg p-4">
          <p className="text-sm text-gray-600 dark:text-gray-400">
            Your communication credits are managed in the SMS & Calling settings.
          </p>
          <a
            href="/settings/sms-calling"
            className="inline-flex items-center gap-1 mt-2 text-sm font-medium text-brand-600 hover:text-brand-700 dark:text-brand-400"
          >
            Manage Credits
            <ExternalLink size={14} />
          </a>
        </div>
      </section>

      {/* Payment Methods */}
      <section className="bg-white dark:bg-gray-800 p-6 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
              <CreditCard size={20} className="text-purple-500" />
              Payment Methods
            </h3>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              Manage your payment methods for subscriptions and credits
            </p>
          </div>
          <button
            onClick={() => setShowAddCard(true)}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-brand-600 border border-brand-600 rounded-lg hover:bg-brand-50 dark:hover:bg-brand-900/20 transition-colors"
          >
            <Plus size={16} />
            Add Card
          </button>
        </div>

        {paymentMethods.length === 0 ? (
          <div className="text-center py-8 text-gray-500 dark:text-gray-400">
            <CreditCard size={40} className="mx-auto mb-2 opacity-30" />
            <p>No payment methods added yet.</p>
            <p className="text-sm mt-1">Add a card to enable auto-reload and subscriptions.</p>
          </div>
        ) : (
          <div className="space-y-3">
            {paymentMethods.map((method) => (
              <div
                key={method.id}
                className="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700"
              >
                <div className="flex items-center gap-4">
                  <div className="w-12 h-8 bg-white dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-600 flex items-center justify-center">
                    {method.brand === 'visa' && (
                      <span className="text-blue-600 font-bold text-sm">VISA</span>
                    )}
                    {method.brand === 'mastercard' && (
                      <span className="text-orange-600 font-bold text-sm">MC</span>
                    )}
                    {method.brand === 'amex' && (
                      <span className="text-blue-800 font-bold text-sm">AMEX</span>
                    )}
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-gray-900 dark:text-white">
                        •••• {method.last4}
                      </span>
                      {method.isDefault && (
                        <span className="px-1.5 py-0.5 text-[10px] font-medium bg-brand-100 text-brand-800 dark:bg-brand-900/30 dark:text-brand-300 rounded flex items-center gap-1">
                          <Star size={10} className="fill-current" /> Default
                        </span>
                      )}
                    </div>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      Expires {method.expMonth}/{method.expYear}
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  {!method.isDefault && (
                    <button
                      className="px-3 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"
                    >
                      Set Default
                    </button>
                  )}
                  <button
                    className="p-2 text-gray-400 hover:text-red-600 dark:hover:text-red-400 transition-colors"
                    title="Remove"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </section>

      {/* Billing History */}
      <section className="bg-white dark:bg-gray-800 p-6 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
              <FileText size={20} className="text-gray-500" />
              Billing History
            </h3>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              View and download your invoices
            </p>
          </div>
        </div>

        <div className="text-center py-8 text-gray-500 dark:text-gray-400">
          <FileText size={40} className="mx-auto mb-2 opacity-30" />
          <p>No invoices yet.</p>
          <p className="text-sm mt-1">Your invoices will appear here after your first payment.</p>
        </div>
      </section>

      {/* Upgrade Modal */}
      {showUpgradeModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b border-gray-200 dark:border-gray-700">
              <div className="flex items-center justify-between">
                <h3 className="text-xl font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                  <Crown className="text-amber-500" />
                  Choose Your Plan
                </h3>
                <button
                  onClick={() => setShowUpgradeModal(false)}
                  className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                  ×
                </button>
              </div>
            </div>

            <div className="p-6">
              {plansLoading ? (
                <div className="flex items-center justify-center py-12">
                  <Loader2 className="animate-spin text-gray-400" size={32} />
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {availablePlans.map((plan) => {
                    const isCurrentPlan = plan.name === currentTier;
                    const isUpgrade = (plan.price_monthly || 0) > (currentPlan?.price_monthly || 0);

                    return (
                      <div
                        key={plan.id}
                        className={`relative border rounded-xl p-5 ${
                          plan.is_most_popular
                            ? 'border-purple-500 ring-2 ring-purple-500/20'
                            : 'border-gray-200 dark:border-gray-700'
                        } ${isCurrentPlan ? 'bg-gray-50 dark:bg-gray-900/50' : ''}`}
                      >
                        {plan.is_most_popular && (
                          <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                            <span className="px-3 py-1 text-xs font-semibold text-white bg-purple-500 rounded-full">
                              Most Popular
                            </span>
                          </div>
                        )}

                        <div className="text-center mb-4">
                          <h4 className="text-lg font-semibold text-gray-900 dark:text-white">
                            {plan.name}
                          </h4>
                          <div className="mt-2">
                            {plan.show_price ? (
                              <>
                                <span className="text-3xl font-bold text-gray-900 dark:text-white">
                                  ${plan.price_monthly || 0}
                                </span>
                                <span className="text-gray-500 dark:text-gray-400">/mo</span>
                              </>
                            ) : (
                              <span className="text-xl font-semibold text-gray-900 dark:text-white">
                                Contact Us
                              </span>
                            )}
                          </div>
                        </div>

                        <ul className="space-y-2 mb-6">
                          {(plan.features || []).slice(0, 6).map((feature, idx) => (
                            <li key={idx} className="flex items-start gap-2 text-sm text-gray-600 dark:text-gray-400">
                              <Check size={16} className="text-green-500 shrink-0 mt-0.5" />
                              {feature}
                            </li>
                          ))}
                        </ul>

                        <button
                          onClick={() => {
                            if (!isCurrentPlan) {
                              handleUpgrade(plan);
                            }
                          }}
                          disabled={isCurrentPlan || checkoutMutation.isPending}
                          className={`w-full py-2.5 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 ${
                            isCurrentPlan
                              ? 'bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-not-allowed'
                              : plan.is_most_popular
                              ? 'bg-purple-600 text-white hover:bg-purple-700'
                              : 'bg-gray-900 dark:bg-white text-white dark:text-gray-900 hover:bg-gray-800 dark:hover:bg-gray-100'
                          }`}
                        >
                          {checkoutMutation.isPending && selectedPlan?.id === plan.id ? (
                            <Loader2 size={18} className="animate-spin" />
                          ) : isCurrentPlan ? (
                            'Current Plan'
                          ) : isUpgrade ? (
                            <>
                              Upgrade <ArrowRight size={16} />
                            </>
                          ) : (
                            'Select'
                          )}
                        </button>
                      </div>
                    );
                  })}
                </div>
              )}

              {/* Transaction Fee Notice */}
              <div className="mt-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                <div className="flex items-start gap-3">
                  <Zap className="text-blue-600 shrink-0 mt-0.5" size={20} />
                  <div>
                    <h4 className="font-medium text-blue-800 dark:text-blue-300">Transaction Fees</h4>
                    <p className="text-sm text-blue-700 dark:text-blue-400 mt-1">
                      Higher tier plans include lower transaction fees on payment processing.
                      Enterprise plans include custom pricing - contact us for details.
                    </p>
                  </div>
                </div>
              </div>
            </div>

            <div className="p-6 border-t border-gray-200 dark:border-gray-700 flex justify-end">
              <button
                onClick={() => setShowUpgradeModal(false)}
                className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Add Card Modal Placeholder */}
      {showAddCard && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-md w-full p-6">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Add Payment Method
            </h3>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
              This will open a secure Stripe checkout to add your card.
            </p>
            <div className="flex justify-end gap-3">
              <button
                onClick={() => setShowAddCard(false)}
                className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              >
                Cancel
              </button>
              <button
                className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors"
              >
                Continue to Stripe
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Cancel Subscription Confirmation Modal */}
      {cancellingSubscription && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-md w-full p-6">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 bg-red-100 dark:bg-red-900/30 rounded-full">
                <AlertCircle className="text-red-600 dark:text-red-400" size={24} />
              </div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                Cancel Subscription
              </h3>
            </div>

            <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
              Are you sure you want to cancel <strong>{cancellingSubscription.plan_name}</strong>?
            </p>

            <div className="space-y-3 mb-6">
              <div className="p-3 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
                <p className="text-sm text-gray-700 dark:text-gray-300">
                  <strong>Cancel at period end:</strong> Your subscription will remain active until{' '}
                  <strong>{formatDate(cancellingSubscription.current_period_end)}</strong>, then it will be cancelled.
                  You can reactivate at any time before that date.
                </p>
              </div>
              <div className="p-3 bg-red-50 dark:bg-red-900/20 rounded-lg border border-red-200 dark:border-red-800">
                <p className="text-sm text-red-700 dark:text-red-300">
                  <strong>Cancel immediately:</strong> Your subscription will be cancelled right now and you may lose access to features immediately.
                </p>
              </div>
            </div>

            {cancelMutation.isError && (
              <div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 rounded-lg text-sm text-red-700 dark:text-red-300">
                Failed to cancel subscription. Please try again.
              </div>
            )}

            <div className="flex flex-col gap-2">
              <button
                onClick={() => cancelMutation.mutate({
                  subscriptionId: cancellingSubscription.stripe_subscription_id,
                  immediate: false,
                })}
                disabled={cancelMutation.isPending}
                className="w-full px-4 py-2.5 text-sm font-medium text-yellow-700 bg-yellow-100 rounded-lg hover:bg-yellow-200 dark:bg-yellow-900/30 dark:text-yellow-300 dark:hover:bg-yellow-900/50 transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
              >
                {cancelMutation.isPending ? (
                  <Loader2 size={16} className="animate-spin" />
                ) : (
                  'Cancel at Period End'
                )}
              </button>
              <button
                onClick={() => cancelMutation.mutate({
                  subscriptionId: cancellingSubscription.stripe_subscription_id,
                  immediate: true,
                })}
                disabled={cancelMutation.isPending}
                className="w-full px-4 py-2.5 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
              >
                {cancelMutation.isPending ? (
                  <Loader2 size={16} className="animate-spin" />
                ) : (
                  'Cancel Immediately'
                )}
              </button>
              <button
                onClick={() => setCancellingSubscription(null)}
                disabled={cancelMutation.isPending}
                className="w-full px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              >
                Keep Subscription
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default BillingSettings;
