1617 lines
73 KiB
TypeScript
1617 lines
73 KiB
TypeScript
/**
|
|
* 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 { createPortal } from 'react-dom';
|
|
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,
|
|
DollarLineIcon,
|
|
} from '../../icons';
|
|
import { Card } from '../../components/ui/card';
|
|
import Badge from '../../components/ui/badge/Badge';
|
|
import Button from '../../components/ui/button/Button';
|
|
import Label from '../../components/form/Label';
|
|
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 { fetchAPI } from '../../services/api';
|
|
import {
|
|
getCreditBalance,
|
|
getCreditPackages,
|
|
getInvoices,
|
|
getAccountPaymentMethods,
|
|
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';
|
|
import PayInvoiceModal from '../../components/billing/PayInvoiceModal';
|
|
import PendingPaymentView from '../../components/billing/PendingPaymentView';
|
|
|
|
/**
|
|
* Helper function to determine the effective currency based on billing country and payment method
|
|
* - PKR for Pakistan users using bank_transfer
|
|
* - USD for all other cases (Stripe, PayPal, or non-PK countries)
|
|
*/
|
|
const getCurrencyForDisplay = (billingCountry: string, paymentMethod?: string): string => {
|
|
if (billingCountry === 'PK' && paymentMethod === 'bank_transfer') {
|
|
return 'PKR';
|
|
}
|
|
return 'USD';
|
|
};
|
|
|
|
/**
|
|
* Convert USD price to PKR using approximate exchange rate
|
|
* Backend uses 278 PKR per USD
|
|
* Rounds to nearest thousand for cleaner display
|
|
*/
|
|
const convertUSDToPKR = (usdAmount: string | number): number => {
|
|
const amount = typeof usdAmount === 'string' ? parseFloat(usdAmount) : usdAmount;
|
|
const pkr = amount * 278;
|
|
return Math.round(pkr / 1000) * 1000; // Round to nearest thousand
|
|
};
|
|
|
|
export default function PlansAndBillingPage() {
|
|
const { startLoading, stopLoading } = usePageLoading();
|
|
const toast = useToast();
|
|
const hasLoaded = useRef(false);
|
|
|
|
// FIX: Subscribe to user changes from Zustand store (reactive)
|
|
const user = useAuthStore((state) => state.user);
|
|
const refreshUser = useAuthStore((state) => state.refreshUser);
|
|
|
|
const isAwsAdmin = user?.account?.slug === 'aws-admin';
|
|
|
|
// Track if initial data has been loaded to prevent flash
|
|
const [initialDataLoaded, setInitialDataLoaded] = useState(false);
|
|
|
|
// Payment processing state - shows beautiful loading UI
|
|
const [paymentProcessing, setPaymentProcessing] = useState<{
|
|
active: boolean;
|
|
stage: 'verifying' | 'processing' | 'finalizing' | 'activating';
|
|
message: string;
|
|
} | null>(null);
|
|
|
|
// 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');
|
|
const [showPayInvoiceModal, setShowPayInvoiceModal] = useState(false);
|
|
const [selectedInvoice, setSelectedInvoice] = useState<Invoice | null>(null);
|
|
|
|
// 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 [userPaymentMethods, setUserPaymentMethods] = 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: false, // FIX: Initialize as false, will be set based on country
|
|
});
|
|
|
|
useEffect(() => {
|
|
if (hasLoaded.current) return;
|
|
hasLoaded.current = true;
|
|
|
|
// Handle payment gateway return URLs BEFORE loadData
|
|
const params = new URLSearchParams(window.location.search);
|
|
const success = params.get('success');
|
|
const sessionId = params.get('session_id'); // Stripe session ID
|
|
const canceled = params.get('canceled');
|
|
const purchase = params.get('purchase');
|
|
const paypalStatus = params.get('paypal');
|
|
const paypalToken = params.get('token'); // PayPal token from URL
|
|
const planIdParam = params.get('plan_id');
|
|
const packageIdParam = params.get('package_id');
|
|
|
|
// Don't destructure from getState - use hooks above instead
|
|
|
|
// ============================================================================
|
|
// PAYMENT RETURN LOGGING - Comprehensive debug output
|
|
// ============================================================================
|
|
const LOG_PREFIX = '[PAYMENT-RETURN]';
|
|
|
|
console.group(`${LOG_PREFIX} Payment Return Flow Started`);
|
|
console.log(`${LOG_PREFIX} Full URL:`, window.location.href);
|
|
console.log(`${LOG_PREFIX} Session ID:`, sessionId);
|
|
|
|
// Detect which payment flow we're in
|
|
const paymentFlow =
|
|
(paypalStatus === 'success' && paypalToken) ? 'PAYPAL_SUCCESS' :
|
|
paypalStatus === 'cancel' ? 'PAYPAL_CANCEL' :
|
|
(success === 'true' && sessionId) ? 'STRIPE_SUCCESS_WITH_SESSION' :
|
|
success === 'true' ? 'STRIPE_SUCCESS_NO_SESSION' :
|
|
canceled === 'true' ? 'STRIPE_CANCELED' :
|
|
purchase === 'success' ? 'CREDIT_PURCHASE_SUCCESS' :
|
|
purchase === 'canceled' ? 'CREDIT_PURCHASE_CANCELED' :
|
|
'NO_PAYMENT_RETURN';
|
|
|
|
console.log(`${LOG_PREFIX} ===== DETECTED PAYMENT FLOW =====`);
|
|
console.log(`${LOG_PREFIX} Flow type:`, paymentFlow);
|
|
console.groupEnd();
|
|
|
|
// Handle PayPal return - Get order_id from localStorage and capture
|
|
if (paypalStatus === 'success' && paypalToken) {
|
|
console.group(`${LOG_PREFIX} PayPal Success Flow`);
|
|
|
|
// FIX: Retrieve order_id from localStorage (stored before redirect)
|
|
const storedOrderId = localStorage.getItem('paypal_order_id');
|
|
|
|
console.log(`${LOG_PREFIX} PayPal token from URL:`, paypalToken);
|
|
console.log(`${LOG_PREFIX} Stored order_id from localStorage:`, storedOrderId);
|
|
console.log(`${LOG_PREFIX} plan_id:`, planIdParam);
|
|
console.log(`${LOG_PREFIX} package_id:`, packageIdParam);
|
|
|
|
if (!storedOrderId) {
|
|
console.error(`${LOG_PREFIX} ❌ CRITICAL: No order_id in localStorage!`);
|
|
console.log(`${LOG_PREFIX} This means order_id was not saved before redirect to PayPal`);
|
|
console.groupEnd();
|
|
toast?.error?.('Payment not captured - order ID missing. Please try again.');
|
|
window.history.replaceState({}, '', window.location.pathname);
|
|
loadData(); // Still load data to show current state
|
|
return;
|
|
}
|
|
|
|
console.log(`${LOG_PREFIX} ✓ Order ID found, proceeding to capture...`);
|
|
|
|
// Show payment processing UI for PayPal
|
|
setPaymentProcessing({
|
|
active: true,
|
|
stage: 'processing',
|
|
message: 'Completing PayPal payment...'
|
|
});
|
|
|
|
// Clean URL immediately
|
|
window.history.replaceState({}, '', window.location.pathname);
|
|
|
|
// Import and capture PayPal order
|
|
import('../../services/billing.api').then(async ({ capturePayPalOrder }) => {
|
|
try {
|
|
const captureResponse = await capturePayPalOrder(storedOrderId, {
|
|
plan_id: planIdParam || undefined,
|
|
package_id: packageIdParam || undefined,
|
|
});
|
|
|
|
console.log(`${LOG_PREFIX} ✓ PayPal capture SUCCESS!`, captureResponse);
|
|
localStorage.removeItem('paypal_order_id');
|
|
|
|
// Update stage
|
|
setPaymentProcessing({
|
|
active: true,
|
|
stage: 'activating',
|
|
message: 'Activating your subscription...'
|
|
});
|
|
|
|
// Refresh user data - IMPORTANT: wait for this!
|
|
try {
|
|
await refreshUser();
|
|
console.log(`${LOG_PREFIX} ✓ User refreshed`);
|
|
} catch (refreshErr) {
|
|
console.error(`${LOG_PREFIX} User refresh failed:`, refreshErr);
|
|
}
|
|
|
|
// Short delay then complete
|
|
setTimeout(() => {
|
|
setPaymentProcessing(null);
|
|
toast?.success?.('Payment completed successfully!');
|
|
loadData();
|
|
}, 500);
|
|
|
|
} catch (err: any) {
|
|
console.error(`${LOG_PREFIX} ❌ PayPal capture FAILED:`, err);
|
|
localStorage.removeItem('paypal_order_id');
|
|
setPaymentProcessing(null);
|
|
toast?.error?.(err?.message || 'Failed to complete PayPal payment');
|
|
loadData();
|
|
}
|
|
});
|
|
|
|
console.groupEnd();
|
|
return; // Don't load data yet, wait for capture to complete
|
|
} else if (paypalStatus === 'cancel') {
|
|
console.log(`${LOG_PREFIX} PayPal payment was cancelled by user`);
|
|
localStorage.removeItem('paypal_order_id'); // Clear on cancellation
|
|
toast?.info?.('PayPal payment was cancelled');
|
|
window.history.replaceState({}, '', window.location.pathname);
|
|
}
|
|
// Handle Stripe return - Verify payment with backend
|
|
else if (success === 'true' && sessionId) {
|
|
console.log(`${LOG_PREFIX} Stripe Success Flow - Session:`, sessionId);
|
|
|
|
// Show beautiful processing UI
|
|
setPaymentProcessing({
|
|
active: true,
|
|
stage: 'verifying',
|
|
message: 'Verifying your payment...'
|
|
});
|
|
|
|
// Clean URL immediately
|
|
window.history.replaceState({}, '', window.location.pathname);
|
|
|
|
fetchAPI(`/v1/billing/stripe/verify-return/?session_id=${sessionId}`)
|
|
.then(async (data) => {
|
|
console.log(`${LOG_PREFIX} Verification response:`, data);
|
|
|
|
if (data.payment_processed) {
|
|
// Payment already processed by webhook!
|
|
setPaymentProcessing({
|
|
active: true,
|
|
stage: 'activating',
|
|
message: 'Activating your subscription...'
|
|
});
|
|
|
|
// Refresh user to get updated account status
|
|
try {
|
|
await refreshUser();
|
|
console.log(`${LOG_PREFIX} User refreshed successfully`);
|
|
} catch (err) {
|
|
console.error(`${LOG_PREFIX} User refresh failed:`, err);
|
|
}
|
|
|
|
// Short delay for UX, then show success
|
|
setTimeout(() => {
|
|
setPaymentProcessing(null);
|
|
toast?.success?.('Payment successful! Your account is now active.');
|
|
loadData();
|
|
}, 500);
|
|
} else if (data.should_poll) {
|
|
// Webhook hasn't fired yet, poll for status
|
|
setPaymentProcessing({
|
|
active: true,
|
|
stage: 'processing',
|
|
message: 'Processing your payment...'
|
|
});
|
|
pollPaymentStatus(sessionId);
|
|
} else {
|
|
setPaymentProcessing(null);
|
|
toast?.warning?.(data.message || 'Payment verification pending');
|
|
loadData();
|
|
}
|
|
})
|
|
.catch(err => {
|
|
console.error(`${LOG_PREFIX} Verification failed:`, err);
|
|
setPaymentProcessing(null);
|
|
toast?.warning?.('Payment verification pending. Please refresh the page.');
|
|
loadData();
|
|
});
|
|
|
|
console.groupEnd();
|
|
return;
|
|
} else if (success === 'true') {
|
|
// Stripe return without session_id (old flow fallback)
|
|
console.log(`${LOG_PREFIX} Stripe success without session_id (legacy flow)`);
|
|
toast?.success?.('Subscription activated successfully!');
|
|
refreshUser().catch(() => {});
|
|
window.history.replaceState({}, '', window.location.pathname);
|
|
} else if (canceled === 'true') {
|
|
console.log(`${LOG_PREFIX} Stripe payment was cancelled`);
|
|
toast?.info?.('Payment was cancelled');
|
|
window.history.replaceState({}, '', window.location.pathname);
|
|
} else if (purchase === 'success') {
|
|
console.log(`${LOG_PREFIX} Credit purchase success`);
|
|
toast?.success?.('Credits purchased successfully!');
|
|
refreshUser().catch(() => {});
|
|
window.history.replaceState({}, '', window.location.pathname);
|
|
} else if (purchase === 'canceled') {
|
|
console.log(`${LOG_PREFIX} Credit purchase cancelled`);
|
|
toast?.info?.('Credit purchase was cancelled');
|
|
window.history.replaceState({}, '', window.location.pathname);
|
|
} else {
|
|
console.log(`${LOG_PREFIX} No payment return parameters detected, loading page normally`);
|
|
}
|
|
|
|
// Helper function to poll payment status with beautiful UI updates
|
|
async function pollPaymentStatus(sessionId: string, attempts = 0) {
|
|
const maxAttempts = 15; // Increased to 15 attempts
|
|
console.log(`${LOG_PREFIX} [POLL] Attempt ${attempts + 1}/${maxAttempts}`);
|
|
|
|
// Update processing stage based on attempt count
|
|
if (attempts === 3) {
|
|
setPaymentProcessing({
|
|
active: true,
|
|
stage: 'finalizing',
|
|
message: 'Finalizing your payment...'
|
|
});
|
|
}
|
|
|
|
if (attempts >= maxAttempts) {
|
|
console.warn(`${LOG_PREFIX} [POLL] Max attempts reached`);
|
|
setPaymentProcessing(null);
|
|
toast?.warning?.('Payment is being processed. Please refresh the page in a moment.');
|
|
loadData();
|
|
return;
|
|
}
|
|
|
|
// Faster initial polls (800ms), slower later (1.5s)
|
|
const pollDelay = attempts < 5 ? 800 : 1500;
|
|
|
|
setTimeout(async () => {
|
|
try {
|
|
const data = await fetchAPI(`/v1/billing/stripe/verify-return/?session_id=${sessionId}`);
|
|
|
|
if (data.payment_processed) {
|
|
console.log(`${LOG_PREFIX} [POLL] Payment processed!`);
|
|
|
|
// Show activating stage
|
|
setPaymentProcessing({
|
|
active: true,
|
|
stage: 'activating',
|
|
message: 'Activating your subscription...'
|
|
});
|
|
|
|
// Refresh user data
|
|
try {
|
|
await refreshUser();
|
|
console.log(`${LOG_PREFIX} [POLL] User refreshed`);
|
|
} catch (err) {
|
|
console.error(`${LOG_PREFIX} [POLL] User refresh failed:`, err);
|
|
}
|
|
|
|
// Short delay then complete
|
|
setTimeout(() => {
|
|
setPaymentProcessing(null);
|
|
toast?.success?.('Payment successful! Your account is now active.');
|
|
loadData();
|
|
}, 500);
|
|
} else {
|
|
// Continue polling
|
|
pollPaymentStatus(sessionId, attempts + 1);
|
|
}
|
|
} catch (pollErr) {
|
|
console.error(`${LOG_PREFIX} [POLL] Error:`, pollErr);
|
|
setPaymentProcessing(null);
|
|
toast?.warning?.('Please refresh page to see updated status.');
|
|
loadData();
|
|
}
|
|
}, pollDelay);
|
|
}
|
|
|
|
// Load data after handling return URLs
|
|
loadData();
|
|
console.groupEnd();
|
|
}, [refreshUser]);
|
|
|
|
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 userMethodsPromise = getAccountPaymentMethods();
|
|
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, userMethodsData] = await Promise.all([
|
|
packagesPromise, invoicesPromise, paymentsPromise, userMethodsPromise
|
|
]);
|
|
|
|
setCreditBalance(balanceData);
|
|
setPackages(packagesData.results || []);
|
|
setInvoices(invoicesData.results || []);
|
|
setPayments(paymentsData.results || []);
|
|
|
|
// Load user's verified payment methods (AccountPaymentMethod)
|
|
const userMethods = (userMethodsData.results || []).filter((m: any) => m.is_enabled !== false);
|
|
setUserPaymentMethods(userMethods);
|
|
|
|
// Select the user's default/verified payment method
|
|
if (userMethods.length > 0) {
|
|
const defaultMethod = userMethods.find((m: any) => m.is_default && m.is_verified) ||
|
|
userMethods.find((m: any) => m.is_verified) ||
|
|
userMethods.find((m: any) => m.is_default) ||
|
|
userMethods[0];
|
|
if (defaultMethod) {
|
|
setSelectedPaymentMethod(defaultMethod.type);
|
|
}
|
|
}
|
|
|
|
// 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 and sync with user's payment method
|
|
try {
|
|
// FIX: Pass billing country to filter payment gateways correctly
|
|
const billingCountry = user?.account?.billing_country || 'US';
|
|
const gateways = await getAvailablePaymentGateways(billingCountry);
|
|
setAvailableGateways(gateways);
|
|
|
|
// Use user's verified payment method to set gateway
|
|
// userMethods was already loaded above
|
|
const verifiedMethod = userMethods.find(
|
|
(m: any) => m.is_verified && m.is_default
|
|
) || userMethods.find((m: any) => m.is_verified) || userMethods[0];
|
|
|
|
let userPreferredGateway: PaymentGateway | null = null;
|
|
if (verifiedMethod) {
|
|
if (verifiedMethod.type === 'stripe' && gateways.stripe) {
|
|
userPreferredGateway = 'stripe';
|
|
} else if (verifiedMethod.type === 'paypal' && gateways.paypal) {
|
|
userPreferredGateway = 'paypal';
|
|
} else if (['bank_transfer', 'local_wallet', 'manual'].includes(verifiedMethod.type)) {
|
|
userPreferredGateway = 'manual';
|
|
}
|
|
}
|
|
|
|
// Set selected gateway based on user preference or available gateways
|
|
if (userPreferredGateway) {
|
|
setSelectedGateway(userPreferredGateway);
|
|
} else 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();
|
|
setInitialDataLoaded(true);
|
|
}
|
|
};
|
|
|
|
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;
|
|
|
|
// FIX: hasActivePlan should check account status, not just plan existence
|
|
const accountStatus = user?.account?.status || '';
|
|
const hasPendingInvoice = invoices.some((inv) => inv.status === 'pending');
|
|
const hasActivePlan = accountStatus === 'active'
|
|
&& effectivePlanId
|
|
&& currentPlan?.slug !== 'free'
|
|
&& !hasPendingInvoice;
|
|
|
|
const hasPendingPayment = payments.some((p) => p.status === 'pending_approval');
|
|
|
|
// Detect new user pending payment scenario:
|
|
// - account status is 'pending_payment'
|
|
// - user has never made a successful payment
|
|
const hasEverPaid = payments.some((p) => p.status === 'succeeded' || p.status === 'completed');
|
|
const isNewUserPendingPayment = accountStatus === 'pending_payment' && !hasEverPaid;
|
|
const pendingInvoice = invoices.find((inv) => inv.status === 'pending');
|
|
const billingCountry = (user?.account as any)?.billing_country || 'US';
|
|
|
|
// FIX: canManageBilling should check if user actually paid via Stripe
|
|
const userPaymentMethod = (user?.account as any)?.payment_method || '';
|
|
const hasStripeCustomerId = !!(user?.account as any)?.stripe_customer_id;
|
|
const canManageBilling = userPaymentMethod === 'stripe' && hasStripeCustomerId && hasActivePlan;
|
|
|
|
// Determine effective currency for display based on country and payment method
|
|
const effectiveCurrency = getCurrencyForDisplay(billingCountry, userPaymentMethod);
|
|
|
|
// Combined check: disable Buy Credits if no active plan OR has pending invoice
|
|
const canBuyCredits = hasActivePlan && !hasPendingInvoice;
|
|
|
|
// 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));
|
|
|
|
// PAYMENT PROCESSING OVERLAY - Beautiful full-page loading with breathing badge
|
|
if (paymentProcessing?.active) {
|
|
const stageConfig = {
|
|
verifying: { color: 'bg-blue-600', label: 'Verifying Payment' },
|
|
processing: { color: 'bg-amber-600', label: 'Processing Payment' },
|
|
finalizing: { color: 'bg-purple-600', label: 'Finalizing' },
|
|
activating: { color: 'bg-green-600', label: 'Activating Subscription' },
|
|
};
|
|
const config = stageConfig[paymentProcessing.stage];
|
|
|
|
// Use Modal-style overlay (matches app's default modal design)
|
|
return createPortal(
|
|
<div className="fixed inset-0 flex items-center justify-center overflow-y-auto modal z-99999">
|
|
{/* Glass-like backdrop - same as Modal component */}
|
|
<div className="fixed inset-0 h-full w-full bg-gray-400/50 backdrop-blur-[32px] dark:bg-gray-900/70"></div>
|
|
|
|
{/* Content card - Modal style */}
|
|
<div className="relative w-full max-w-md mx-4 rounded-3xl bg-white dark:bg-gray-900 shadow-xl p-8">
|
|
{/* Main Loading Spinner */}
|
|
<div className="relative w-20 h-20 mx-auto mb-6">
|
|
<div className="absolute inset-0 rounded-full border-4 border-gray-200 dark:border-gray-700"></div>
|
|
<div className="absolute inset-0 rounded-full border-4 border-transparent border-t-brand-500 animate-spin"></div>
|
|
<div className="absolute inset-2 rounded-full border-4 border-transparent border-t-brand-400 animate-spin" style={{ animationDirection: 'reverse', animationDuration: '1.5s' }}></div>
|
|
</div>
|
|
|
|
{/* Message */}
|
|
<h2 className="text-xl text-gray-900 dark:text-white font-bold text-center mb-2">
|
|
{paymentProcessing.message}
|
|
</h2>
|
|
<p className="text-gray-500 dark:text-gray-400 text-sm text-center mb-6">
|
|
Please don't close this page
|
|
</p>
|
|
|
|
{/* Stage Badge */}
|
|
<div className="flex justify-center">
|
|
<span className={`inline-flex items-center gap-2 px-4 py-2 rounded-full text-white text-sm font-medium ${config.color} shadow-md`}>
|
|
<Loader2Icon className="w-4 h-4 animate-spin" />
|
|
{config.label}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
</div>,
|
|
document.body
|
|
);
|
|
}
|
|
|
|
// Show loading spinner until initial data is loaded
|
|
// This prevents the flash of billing dashboard before PendingPaymentView
|
|
if (!initialDataLoaded) {
|
|
return (
|
|
<div className="flex items-center justify-center min-h-[400px]">
|
|
<div className="text-center">
|
|
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-500 mx-auto mb-4"></div>
|
|
<p className="text-gray-500 dark:text-gray-400">Loading billing information...</p>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// NEW USER PENDING PAYMENT - Show full-page payment view
|
|
// This is the simplified flow for users who just signed up with a paid plan
|
|
if (isNewUserPendingPayment && pendingInvoice) {
|
|
const planName = currentPlan?.name || pendingInvoice.subscription?.plan?.name || 'Selected Plan';
|
|
const invoiceCurrency = pendingInvoice.currency || 'USD';
|
|
|
|
// Get USD price from plan, PKR price from invoice
|
|
const planUSDPrice = currentPlan?.price || pendingInvoice.subscription?.plan?.price || '0';
|
|
const invoicePKRPrice = invoiceCurrency === 'PKR' ? (pendingInvoice.total_amount || pendingInvoice.total || '0') : undefined;
|
|
|
|
// Check if user has a pending bank transfer (status = pending_approval with payment_method = bank_transfer)
|
|
const hasPendingBankTransfer = payments.some(
|
|
(p) => p.status === 'pending_approval' && (p.payment_method === 'bank_transfer' || p.payment_method === 'manual')
|
|
);
|
|
|
|
// Debug log for payment view
|
|
console.log('[PlansAndBillingPage] Rendering PendingPaymentView:', {
|
|
billingCountry,
|
|
invoiceCurrency,
|
|
planUSDPrice,
|
|
invoicePKRPrice,
|
|
planName,
|
|
hasPendingBankTransfer
|
|
});
|
|
|
|
return (
|
|
<PendingPaymentView
|
|
invoice={pendingInvoice}
|
|
userCountry={billingCountry}
|
|
planName={planName}
|
|
planPrice={planUSDPrice}
|
|
planPricePKR={invoicePKRPrice}
|
|
currency={invoiceCurrency}
|
|
hasPendingBankTransfer={hasPendingBankTransfer}
|
|
onPaymentSuccess={() => {
|
|
// Refresh user and billing data
|
|
const { refreshUser } = useAuthStore.getState();
|
|
refreshUser().catch(() => {});
|
|
loadData();
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
// EXISTING USER - Show normal billing dashboard
|
|
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-200 via-brand-100 to-indigo-200 dark:from-brand-900/50 dark:via-brand-800/40 dark:to-indigo-900/40 border border-brand-300 dark:border-brand-600">
|
|
<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-brand-900 dark:text-white">
|
|
{currentPlan?.name || 'No Plan'}
|
|
</h2>
|
|
<Badge variant="solid" tone={hasActivePlan ? 'success' : 'warning'}>
|
|
{hasActivePlan ? 'Active' : 'Inactive'}
|
|
</Badge>
|
|
</div>
|
|
<p className="text-brand-700 dark:text-brand-200">
|
|
{currentPlan?.description || 'Select a plan to unlock features'}
|
|
</p>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
{canManageBilling && (
|
|
<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/80 dark:bg-gray-800/60 rounded-xl shadow-sm">
|
|
<div className="flex items-center gap-2 text-sm text-brand-700 dark:text-brand-300 mb-1">
|
|
<ZapIcon className="w-4 h-4 text-brand-600" />
|
|
Credits
|
|
</div>
|
|
<div className="text-2xl font-bold text-brand-900 dark:text-white">
|
|
{creditBalance?.credits?.toLocaleString() || 0}
|
|
</div>
|
|
<div className="text-xs text-brand-600 dark:text-brand-400 mt-1">Available now</div>
|
|
</div>
|
|
<div className="p-4 bg-white/80 dark:bg-gray-800/60 rounded-xl shadow-sm">
|
|
<div className="flex items-center gap-2 text-sm text-purple-700 dark:text-purple-300 mb-1">
|
|
<TrendingUpIcon className="w-4 h-4 text-purple-600" />
|
|
Used
|
|
</div>
|
|
<div className="text-2xl font-bold text-purple-900 dark:text-white">
|
|
{creditBalance?.credits_used_this_month?.toLocaleString() || 0}
|
|
</div>
|
|
<div className="text-xs text-purple-600 dark:text-purple-400 mt-1">This month ({creditUsage}%)</div>
|
|
</div>
|
|
<div className="p-4 bg-white/80 dark:bg-gray-800/60 rounded-xl shadow-sm">
|
|
<div className="flex items-center gap-2 text-sm text-success-700 dark:text-success-300 mb-1">
|
|
<CalendarIcon className="w-4 h-4 text-success-600" />
|
|
Renews
|
|
</div>
|
|
<div className="text-2xl font-bold text-success-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-success-600 dark:text-success-400 mt-1">Next billing</div>
|
|
</div>
|
|
<div className="p-4 bg-white/80 dark:bg-gray-800/60 rounded-xl shadow-sm">
|
|
<div className="flex items-center gap-2 text-sm text-amber-700 dark:text-amber-300 mb-1">
|
|
<WalletIcon className="w-4 h-4 text-amber-600" />
|
|
Monthly
|
|
</div>
|
|
<div className="text-2xl font-bold text-amber-900 dark:text-white">
|
|
{formatCurrency(Number(currentPlan?.price || 0), 'USD')}
|
|
</div>
|
|
<div className="text-xs text-amber-600 dark:text-amber-400 mt-1">
|
|
{billingCountry === 'PK' ? (
|
|
<>≈ PKR {convertUSDToPKR(Number(currentPlan?.price || 0)).toLocaleString()}/mo</>
|
|
) : (
|
|
'Per month'
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Credit Usage Bar */}
|
|
<div className="mt-6 pt-6 border-t border-brand-200/50 dark:border-brand-700/30">
|
|
<div className="flex justify-between text-sm mb-2">
|
|
<span className="text-brand-700 dark:text-brand-300">Credit Usage</span>
|
|
<span className="font-medium text-brand-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 gap-3 mb-4">
|
|
<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>
|
|
|
|
{/* Show message if no active plan */}
|
|
{!hasActivePlan ? (
|
|
<div className="text-center py-8 border-2 border-dashed border-gray-200 dark:border-gray-700 rounded-xl">
|
|
<LockIcon className="w-8 h-8 mx-auto text-gray-400 mb-2" />
|
|
<p className="text-gray-500 dark:text-gray-400 text-sm">
|
|
Subscribe to a plan first to purchase additional credits
|
|
</p>
|
|
</div>
|
|
) : hasPendingInvoice ? (
|
|
<div className="text-center py-8 border-2 border-dashed border-warning-200 dark:border-warning-700 bg-warning-50 dark:bg-warning-900/20 rounded-xl">
|
|
<AlertCircleIcon className="w-8 h-8 mx-auto text-warning-500 mb-2" />
|
|
<p className="text-warning-700 dark:text-warning-300 text-sm font-medium">
|
|
Please pay your pending invoice first
|
|
</p>
|
|
<p className="text-warning-600 dark:text-warning-400 text-xs mt-1">
|
|
Credit purchases are disabled until your outstanding balance is settled
|
|
</p>
|
|
</div>
|
|
) : (
|
|
<>
|
|
{/* Payment Method Selector - Clear buttons */}
|
|
{(availableGateways.stripe || availableGateways.paypal) && (
|
|
<div className="mb-4">
|
|
<Label className="text-xs text-gray-500 dark:text-gray-400 mb-2 block">Payment Method</Label>
|
|
<div className="flex gap-2">
|
|
{availableGateways.stripe && (
|
|
<button
|
|
onClick={() => setSelectedGateway('stripe')}
|
|
className={`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-lg border-2 transition-all ${
|
|
selectedGateway === 'stripe'
|
|
? 'border-brand-500 bg-brand-50 dark:bg-brand-900/20 text-brand-700 dark:text-brand-300'
|
|
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
|
|
}`}
|
|
>
|
|
<CreditCardIcon className={`w-5 h-5 ${selectedGateway === 'stripe' ? 'text-brand-600' : 'text-gray-500'}`} />
|
|
<span className="text-sm font-medium">Credit/Debit Card</span>
|
|
</button>
|
|
)}
|
|
{availableGateways.paypal && (
|
|
<button
|
|
onClick={() => setSelectedGateway('paypal')}
|
|
className={`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-lg border-2 transition-all ${
|
|
selectedGateway === 'paypal'
|
|
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300'
|
|
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
|
|
}`}
|
|
>
|
|
<WalletIcon className={`w-5 h-5 ${selectedGateway === 'paypal' ? 'text-blue-600' : 'text-gray-500'}`} />
|
|
<span className="text-sm font-medium">PayPal</span>
|
|
</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">
|
|
{formatCurrency(pkg.price, 'USD')}
|
|
</div>
|
|
{billingCountry === 'PK' && (
|
|
<div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
|
|
≈ PKR {convertUSDToPKR(pkg.price).toLocaleString()}
|
|
</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">
|
|
{formatCurrency(plan.price, 'USD')}/mo
|
|
</div>
|
|
{billingCountry === 'PK' && (
|
|
<div className="text-xs text-gray-500 dark:text-gray-400">
|
|
≈ PKR {convertUSDToPKR(plan.price).toLocaleString()}/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">
|
|
<div className="font-semibold text-gray-900 dark:text-white">
|
|
{formatCurrency(invoice.total_amount, 'USD')}
|
|
</div>
|
|
{billingCountry === 'PK' && invoice.currency === 'USD' && (
|
|
<div className="text-xs text-gray-500 dark:text-gray-400">
|
|
≈ PKR {convertUSDToPKR(invoice.total_amount).toLocaleString()}
|
|
</div>
|
|
)}
|
|
</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">
|
|
<div className="flex items-center justify-end gap-2">
|
|
{invoice.status === 'pending' && (
|
|
<Button
|
|
size="sm"
|
|
variant="primary"
|
|
tone="brand"
|
|
startIcon={<DollarLineIcon className="w-4 h-4" />}
|
|
onClick={() => {
|
|
setSelectedInvoice(invoice);
|
|
setShowPayInvoiceModal(true);
|
|
}}
|
|
>
|
|
Pay Now
|
|
</Button>
|
|
)}
|
|
<Button
|
|
size="sm"
|
|
variant="ghost"
|
|
tone="neutral"
|
|
startIcon={<DownloadIcon className="w-4 h-4" />}
|
|
onClick={() => handleDownloadInvoice(invoice.id)}
|
|
>
|
|
PDF
|
|
</Button>
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
))
|
|
)}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</Card>
|
|
|
|
{/* SECTION 4: Payment Methods - User's verified 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">Your saved payment methods</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
|
{userPaymentMethods
|
|
.filter((method: any) => {
|
|
// Bank transfer is only available for Pakistani users
|
|
if (method.type === 'bank_transfer' && billingCountry !== 'PK') {
|
|
return false;
|
|
}
|
|
return true;
|
|
})
|
|
.map((method: any) => (
|
|
<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' || method.type === 'local_wallet' ? (
|
|
<Building2Icon className="w-6 h-6 text-gray-500" />
|
|
) : method.type === 'paypal' ? (
|
|
<WalletIcon className="w-6 h-6 text-blue-500" />
|
|
) : (
|
|
<CreditCardIcon className="w-6 h-6 text-brand-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>
|
|
<div className="flex flex-col gap-1 items-end">
|
|
{method.is_verified && (
|
|
<Badge variant="soft" tone="success" size="sm">Verified</Badge>
|
|
)}
|
|
{method.is_default && (
|
|
<Badge variant="soft" tone="brand" size="sm">Default</Badge>
|
|
)}
|
|
</div>
|
|
</div>
|
|
{selectedPaymentMethod !== method.type ? (
|
|
<Button
|
|
size="sm"
|
|
variant="outline"
|
|
tone="neutral"
|
|
className="w-full"
|
|
onClick={() => {
|
|
setSelectedPaymentMethod(method.type);
|
|
// Sync gateway selection
|
|
if (method.type === 'stripe' && availableGateways.stripe) {
|
|
setSelectedGateway('stripe');
|
|
} else if (method.type === 'paypal' && availableGateways.paypal) {
|
|
setSelectedGateway('paypal');
|
|
} else {
|
|
setSelectedGateway('manual');
|
|
}
|
|
}}
|
|
>
|
|
Select
|
|
</Button>
|
|
) : (
|
|
<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>
|
|
))}
|
|
{userPaymentMethods.length === 0 && (
|
|
<div className="col-span-full text-center py-8 text-gray-500 dark:text-gray-400">
|
|
<CreditCardIcon className="w-8 h-8 mx-auto mb-2 opacity-50" />
|
|
<p>No payment methods saved yet.</p>
|
|
<p className="text-xs mt-1">Complete a payment to save your method.</p>
|
|
</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>
|
|
)}
|
|
|
|
{/* Pay Invoice Modal */}
|
|
{showPayInvoiceModal && selectedInvoice && (
|
|
<PayInvoiceModal
|
|
isOpen={showPayInvoiceModal}
|
|
onClose={() => {
|
|
setShowPayInvoiceModal(false);
|
|
setSelectedInvoice(null);
|
|
}}
|
|
onSuccess={async () => {
|
|
setShowPayInvoiceModal(false);
|
|
setSelectedInvoice(null);
|
|
// Refresh user and billing data
|
|
const { refreshUser } = useAuthStore.getState();
|
|
await refreshUser();
|
|
await loadData();
|
|
toast?.success?.('Payment processed successfully!');
|
|
}}
|
|
invoice={selectedInvoice}
|
|
userCountry={(user?.account as any)?.billing_country || 'US'}
|
|
defaultPaymentMethod={selectedPaymentMethod}
|
|
/>
|
|
)}
|
|
</>
|
|
);
|
|
}
|