import React from 'react'; import { AlertTriangle, Loader2, RefreshCw, Sparkles, ArrowUpRight } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; import { CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Separator } from '@/components/ui/separator'; import { AdminLayout } from '../components/AdminLayout'; import { getTenantPackagesOverview, getTenantPaddleTransactions, PaddleTransactionSummary, TenantPackageSummary } from '../api'; import { isAuthError } from '../auth/tokens'; import { TenantHeroCard, FrostedCard, FrostedSurface, tenantHeroPrimaryButtonClass, tenantHeroSecondaryButtonClass, } from '../components/tenant'; type PackageWarning = { id: string; tone: 'warning' | 'danger'; message: string }; export default function BillingPage() { const { t, i18n } = useTranslation(['management', 'dashboard']); const locale = React.useMemo( () => (i18n.language?.startsWith('en') ? 'en-GB' : 'de-DE'), [i18n.language] ); const [packages, setPackages] = React.useState([]); const [activePackage, setActivePackage] = React.useState(null); const [transactions, setTransactions] = React.useState([]); const [transactionCursor, setTransactionCursor] = React.useState(null); const [transactionsHasMore, setTransactionsHasMore] = React.useState(false); const [transactionsLoading, setTransactionsLoading] = React.useState(false); const [loading, setLoading] = React.useState(true); const [error, setError] = React.useState(null); const formatDate = React.useCallback( (value: string | null | undefined) => { if (!value) return '--'; const date = new Date(value); if (Number.isNaN(date.getTime())) return '--'; return date.toLocaleDateString(locale, { day: '2-digit', month: 'short', year: 'numeric' }); }, [locale] ); const formatCurrency = React.useCallback( (value: number | null | undefined, currency = 'EUR') => { if (value === null || value === undefined) return '--'; return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value); }, [locale] ); const packageLabels = React.useMemo( () => ({ statusActive: t('billing.sections.packages.card.statusActive'), statusInactive: t('billing.sections.packages.card.statusInactive'), used: t('billing.sections.packages.card.used'), available: t('billing.sections.packages.card.available'), expires: t('billing.sections.packages.card.expires'), }), [t] ); const loadAll = React.useCallback(async (force = false) => { setLoading(true); setError(null); try { const [packagesResult, paddleTransactions] = await Promise.all([ getTenantPackagesOverview(force ? { force: true } : undefined), getTenantPaddleTransactions().catch((err) => { console.warn('Failed to load Paddle transactions', err); return { data: [] as PaddleTransactionSummary[], nextCursor: null, hasMore: false }; }), ]); setPackages(packagesResult.packages); setActivePackage(packagesResult.activePackage); setTransactions(paddleTransactions.data); setTransactionCursor(paddleTransactions.nextCursor); setTransactionsHasMore(paddleTransactions.hasMore); } catch (err) { if (!isAuthError(err)) { setError(t('billing.errors.load')); } } finally { setLoading(false); } }, [t]); const loadMoreTransactions = React.useCallback(async () => { if (!transactionsHasMore || transactionsLoading || !transactionCursor) { return; } setTransactionsLoading(true); try { const result = await getTenantPaddleTransactions(transactionCursor); setTransactions((current) => [...current, ...result.data]); setTransactionCursor(result.nextCursor); setTransactionsHasMore(result.hasMore && Boolean(result.nextCursor)); } catch (error) { console.warn('Failed to load additional Paddle transactions', error); setTransactionsHasMore(false); } finally { setTransactionsLoading(false); } }, [transactionCursor, transactionsHasMore, transactionsLoading]); React.useEffect(() => { void loadAll(); }, [loadAll]); const activeWarnings = React.useMemo( () => buildPackageWarnings(activePackage, t, formatDate, 'billing.sections.overview.warnings'), [activePackage, t, formatDate], ); const heroBadge = t('billing.hero.badge', 'Abrechnung'); const heroDescription = t('billing.hero.description', 'Behalte Laufzeiten, Rechnungen und Limits deiner Pakete im Blick.'); const heroSupporting: string[] = [ activePackage ? t('billing.hero.summary.active', 'Aktives Paket: {{name}}', { name: activePackage.package_name }) : t('billing.hero.summary.inactive', 'Noch kein aktives Paket – wählt ein Kontingent, das zu euch passt.'), t('billing.hero.summary.transactions', '{{count}} Zahlungen synchronisiert', { count: transactions.length }) ]; const packagesHref = `/${i18n.language?.split('-')[0] ?? 'de'}/packages`; const heroPrimaryAction = ( ); const heroSecondaryAction = ( ); const nextRenewalLabel = t('billing.hero.nextRenewal', 'Verlängerung am'); const topWarning = activeWarnings[0]; const heroAside = (

{t('billing.hero.activePackage', 'Aktuelles Paket')}

{activePackage?.package_name ?? t('billing.hero.activeFallback', 'Noch nicht ausgewählt')}

{nextRenewalLabel}

{formatDate(activePackage?.expires_at)}

{topWarning ? (
{topWarning.message}
) : null}
); return ( {error && ( {t('dashboard:alerts.errorTitle')} {error} )} {loading ? ( ) : ( <>
{t('billing.sections.overview.title')} {t('billing.sections.overview.description')}
{activePackage ? activePackage.package_name : t('billing.sections.overview.emptyBadge')}
{activePackage ? (
{activeWarnings.length > 0 && (
{activeWarnings.map((warning) => ( {warning.message} ))}
)}
) : ( )}
{t('billing.sections.packages.title')} {t('billing.sections.packages.description')} {packages.length === 0 ? ( ) : ( packages.map((pkg) => { const warnings = buildPackageWarnings(pkg, t, formatDate, 'billing.sections.packages.card.warnings'); return ( ); }) )} {t('billing.sections.transactions.title')} {t('billing.sections.transactions.description')} {transactions.length === 0 ? ( ) : (
{transactions.map((transaction) => ( ))}
)} {transactionsHasMore && ( )}
)}
); } function TransactionCard({ transaction, formatCurrency, formatDate, locale, t, }: { transaction: PaddleTransactionSummary; formatCurrency: (value: number | null | undefined, currency?: string) => string; formatDate: (value: string | null | undefined) => string; locale: string; t: (key: string, options?: Record) => string; }) { const amount = transaction.grand_total ?? transaction.amount ?? null; const currency = transaction.currency ?? 'EUR'; const createdAtIso = transaction.created_at ?? null; const createdAt = createdAtIso ? new Date(createdAtIso) : null; const createdLabel = createdAt ? createdAt.toLocaleString(locale, { year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit', }) : formatDate(createdAtIso); const statusKey = transaction.status ? `billing.sections.transactions.status.${transaction.status}` : 'billing.sections.transactions.status.unknown'; const statusText = t(statusKey, { defaultValue: (transaction.status ?? 'unknown').replace(/_/g, ' '), }); return (

{t('billing.sections.transactions.labels.transactionId', { id: transaction.id ?? '—' })}

{createdLabel}

{transaction.checkout_id ? (

{t('billing.sections.transactions.labels.checkoutId', { id: transaction.checkout_id })}

) : null} {transaction.origin ? (

{t('billing.sections.transactions.labels.origin', { origin: transaction.origin })}

) : null}
{statusText}
{formatCurrency(amount, currency)}
{transaction.tax !== undefined && transaction.tax !== null ? ( {t('billing.sections.transactions.labels.tax', { value: formatCurrency(transaction.tax, currency) })} ) : null} {transaction.receipt_url ? ( {t('billing.sections.transactions.labels.receipt')} ) : null}
); } function InfoCard({ label, value, helper, tone, }: { label: string; value: string | number | null | undefined; helper?: string; tone: 'pink' | 'amber' | 'sky' | 'emerald'; }) { const toneBorders: Record<'pink' | 'amber' | 'sky' | 'emerald', string> = { pink: 'border-pink-200/60 shadow-rose-200/30', amber: 'border-amber-200/60 shadow-amber-200/30', sky: 'border-sky-200/60 shadow-sky-200/30', emerald: 'border-emerald-200/60 shadow-emerald-200/30', } as const; return ( {label}
{value ?? '--'}
{helper ?

{helper}

: null}
); } function PackageCard({ pkg, isActive, labels, formatDate, formatCurrency, warnings = [], }: { pkg: TenantPackageSummary; isActive: boolean; labels: { statusActive: string; statusInactive: string; used: string; available: string; expires: string; }; formatDate: (value: string | null | undefined) => string; formatCurrency: (value: number | null | undefined, currency?: string) => string; warnings?: PackageWarning[]; }) { return ( {warnings.length > 0 && (
{warnings.map((warning) => ( {warning.message} ))}
)}

{pkg.package_name}

{formatDate(pkg.purchased_at)} · {formatCurrency(pkg.price, pkg.currency ?? 'EUR')}

{isActive ? labels.statusActive : labels.statusInactive}
{labels.used}: {pkg.used_events} {labels.available}: {pkg.remaining_events ?? '--'} {labels.expires}: {formatDate(pkg.expires_at)}
); } function EmptyState({ message }: { message: string }) { return (

{message}

); } function buildPackageWarnings( pkg: TenantPackageSummary | null | undefined, translate: (key: string, options?: Record) => string, formatDate: (value: string | null | undefined) => string, keyPrefix: string, ): PackageWarning[] { if (!pkg) { return []; } const warnings: PackageWarning[] = []; const remaining = typeof pkg.remaining_events === 'number' ? pkg.remaining_events : null; if (remaining !== null) { if (remaining <= 0) { warnings.push({ id: `${pkg.id}-no-events`, tone: 'danger', message: translate(`${keyPrefix}.noEvents`), }); } else if (remaining <= 2) { warnings.push({ id: `${pkg.id}-low-events`, tone: 'warning', message: translate(`${keyPrefix}.lowEvents`, { remaining }), }); } } const expiresAt = pkg.expires_at ? new Date(pkg.expires_at) : null; if (expiresAt && !Number.isNaN(expiresAt.getTime())) { const now = new Date(); const diffMillis = expiresAt.getTime() - now.getTime(); const diffDays = Math.ceil(diffMillis / (1000 * 60 * 60 * 24)); const formatted = formatDate(pkg.expires_at); if (diffDays < 0) { warnings.push({ id: `${pkg.id}-expired`, tone: 'danger', message: translate(`${keyPrefix}.expired`, { date: formatted }), }); } else if (diffDays <= 14) { warnings.push({ id: `${pkg.id}-expires`, tone: 'warning', message: translate(`${keyPrefix}.expiresSoon`, { date: formatted }), }); } } return warnings; } function BillingSkeleton() { return (
{Array.from({ length: 3 }).map((_, index) => (
{Array.from({ length: 4 }).map((__, placeholderIndex) => (
))}
))}
); }