import { useState, useEffect, useCallback } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import QRCode from 'qrcode'; import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft, Gift, Plus, History, DollarSign, Printer, Download } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Badge } from '@/components/ui/badge'; import { Skeleton } from '@/components/ui/skeleton'; import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'; import { useToast } from '@/hooks/useToast'; import { createAIClient } from '@/lib/ai-client'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useAppContext } from '@/hooks/useAppContext'; import { AIProvider } from '@/contexts/AISettingsContext'; interface CreditsDialogProps { open: boolean; onOpenChange: (open: boolean) => void; provider: AIProvider; } interface Payment { object: 'payment'; id: string; status: 'pending' | 'completed' | 'failed' | 'expired'; amount: number; fee: number; total: number; method: 'stripe' | 'lightning'; description: string; url: string; created_at: number; completed_at?: number; expires_at: number; } interface PaymentsResponse { object: 'list'; data: Payment[]; has_more: boolean; url: string; } interface AddCreditsRequest { amount: number; method: 'stripe' | 'lightning'; redirect_url?: string; } interface Giftcard { object: 'giftcard'; id: string; code: string; amount: number; redeemed: boolean; created_at?: number; } interface GiftcardsResponse { object: 'list'; data: Giftcard[]; has_more: boolean; } interface CreateGiftcardRequest { amount: number; quantity: number; } interface RedeemGiftcardRequest { code: string; } interface GiftcardRedemption { object: 'giftcard_redemption'; amount: number; } const PRESET_AMOUNTS = [5, 10, 25, 50, 100]; interface LightningPaymentProps { invoice: string; amount: number; paymentId: string; provider: AIProvider; onClose: () => void; onPaymentCompleted: () => void; } function LightningPayment({ invoice, amount, paymentId, provider, onClose, onPaymentCompleted }: LightningPaymentProps) { const { t } = useTranslation(); const { user } = useCurrentUser(); const { config } = useAppContext(); const queryClient = useQueryClient(); const [qrDataUrl, setQrDataUrl] = useState(''); const [isWebLNAvailable, setIsWebLNAvailable] = useState(false); const [isPayingWithWebLN, setIsPayingWithWebLN] = useState(false); const [showCopiedTooltip, setShowCopiedTooltip] = useState(false); const [paymentCompleted, setPaymentCompleted] = useState(false); const { toast } = useToast(); const formatCurrency = useCallback((amount: number) => { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2, }).format(amount); }, []); useEffect(() => { // Generate QR code QRCode.toDataURL(invoice, { width: 256, margin: 2, color: { dark: '#000000', light: '#ffffff', }, }) .then(setQrDataUrl) .catch(console.error); // Check for WebLN availability setIsWebLNAvailable(typeof window !== 'undefined' && 'webln' in window); }, [invoice]); // Poll payment status useEffect(() => { // Don't poll if payment already completed if (paymentCompleted) return; let intervalId: NodeJS.Timeout | null = null; const pollPaymentStatus = async () => { // Double-check in case state updated during async operation if (paymentCompleted) return; try { const ai = createAIClient(provider, user, config.corsProxy); const payment = await ai.get(`/credits/payments/${paymentId}`) as Payment; if (payment.status === 'completed') { // Mark as completed to prevent further polling setPaymentCompleted(true); // Clear the interval immediately if (intervalId) { clearInterval(intervalId); intervalId = null; } // Update credits balance queryClient.invalidateQueries({ queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); // Update payments list queryClient.invalidateQueries({ queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); // Show toast toast({ title: t('paymentCompleted'), description: t('creditsAddedToAccount', { amount: formatCurrency(payment.amount) }), }); // Close dialog immediately onPaymentCompleted(); } else if (payment.status === 'failed') { // Mark as completed to prevent further polling setPaymentCompleted(true); // Clear the interval immediately if (intervalId) { clearInterval(intervalId); intervalId = null; } toast({ title: t('paymentFailed'), description: t('paymentFailed'), variant: 'destructive', }); } else if (payment.status === 'expired') { // Mark as completed to prevent further polling setPaymentCompleted(true); // Clear the interval immediately if (intervalId) { clearInterval(intervalId); intervalId = null; } toast({ title: t('paymentExpired'), description: t('paymentExpiredMessage'), variant: 'destructive', }); } } catch (error) { console.error('Failed to poll payment status:', error); } }; // Poll immediately on mount pollPaymentStatus(); // Then poll every 3 seconds intervalId = setInterval(pollPaymentStatus, 3000); return () => { if (intervalId) { clearInterval(intervalId); } }; }, [paymentId, provider, user, config.corsProxy, queryClient, toast, t, onPaymentCompleted, formatCurrency, paymentCompleted]); const handleWebLNPay = async () => { if (!window.webln) return; try { setIsPayingWithWebLN(true); await window.webln.enable(); await window.webln.sendPayment(invoice); toast({ title: t('paymentSent'), description: t('lightningPaymentSent'), }); onClose(); } catch (error) { console.error('WebLN payment failed:', error); toast({ title: t('paymentFailed'), description: error instanceof Error ? error.message : t('failedToSendLightning'), variant: 'destructive', }); } finally { setIsPayingWithWebLN(false); } }; const handleCopyInvoice = () => { navigator.clipboard.writeText(invoice); setShowCopiedTooltip(true); setTimeout(() => setShowCopiedTooltip(false), 2000); }; return (

{t('lightningPayment')}

{t('payWithLightning', { amount: formatCurrency(amount) })}

{/* QR Code */}
{qrDataUrl ? (
Lightning Invoice QR Code
) : (
)}
{/* Payment Buttons */}
{isWebLNAvailable && ( )}
{showCopiedTooltip && (
{t('copied')}
)}
); } export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogProps) { const { t } = useTranslation(); const { user } = useCurrentUser(); const { config } = useAppContext(); const { toast } = useToast(); const queryClient = useQueryClient(); const [amount, setAmount] = useState(10); const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe'); const [lightningInvoice, setLightningInvoice] = useState(null); const [lightningPaymentId, setLightningPaymentId] = useState(null); const [refreshingPayments, setRefreshingPayments] = useState>(new Set()); const [giftcardAmount, setGiftcardAmount] = useState(10); const [giftcardQuantity, setGiftcardQuantity] = useState(1); const [redeemCode, setRedeemCode] = useState(''); const [copiedCode, setCopiedCode] = useState(null); const [isPrintingQRCodes, setIsPrintingQRCodes] = useState(false); // Query for payment preview (to get fee information) // This creates a payment invoice in advance so we can show the fee const { data: paymentPreview, isLoading: isLoadingPreview } = useQuery({ queryKey: ['ai-payment-preview', provider.nostr ? user?.pubkey ?? '' : '', provider.id, amount, paymentMethod], queryFn: async (): Promise => { const ai = createAIClient(provider, user, config.corsProxy); const request: AddCreditsRequest = { amount, method: paymentMethod, }; if (paymentMethod === 'stripe') { request.redirect_url = window.location.origin + '/settings/ai'; } return await ai.post('/credits/add', { body: request, }) as Payment; }, enabled: open && amount > 0, retry: false, refetchOnWindowFocus: false, staleTime: Infinity, // Don't auto-refetch, we'll manually refetch when needed gcTime: 1000 * 60 * 10, // Keep in cache for 10 minutes }); // Query for payment history const { data: payments, isLoading: isLoadingPayments } = useQuery({ queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], queryFn: async (): Promise => { const ai = createAIClient(provider, user, config.corsProxy); const data = await ai.get('/credits/payments?status=completed&limit=50') as PaymentsResponse; return data.data; }, enabled: open, retry: false, refetchOnWindowFocus: false, }); // Query for gift cards const { data: giftcards, isLoading: isLoadingGiftcards } = useQuery({ queryKey: ['ai-giftcards', provider.nostr ? user?.pubkey ?? '' : '', provider.id], queryFn: async (): Promise => { const ai = createAIClient(provider, user, config.corsProxy); const data = await ai.get('/credits/giftcards?limit=50') as GiftcardsResponse; return data.data; }, enabled: open, retry: false, refetchOnWindowFocus: false, }); // Mutation for adding credits const addCreditsMutation = useMutation({ mutationFn: async (request: AddCreditsRequest): Promise => { const ai = createAIClient(provider, user, config.corsProxy); return await ai.post('/credits/add', { body: request, }) as Payment; }, onSuccess: (payment) => { if (payment.method === 'stripe') { // Open Stripe checkout in new window window.open(payment.url, '_blank'); toast({ title: t('paymentInitiated'), description: t('stripeCheckoutOpened'), }); } else if (payment.method === 'lightning') { // Show Lightning payment interface setLightningInvoice(payment.url); setLightningPaymentId(payment.id); } // Refresh payments list queryClient.invalidateQueries({ queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); // Refresh credits balance queryClient.invalidateQueries({ queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); }, onError: (error: Error) => { const errorMessage = error?.message || t('paymentFailed'); toast({ title: t('paymentFailed'), description: errorMessage, variant: 'destructive', }); }, }); // Mutation for checking payment status const checkPaymentMutation = useMutation({ mutationFn: async (paymentId: string): Promise => { const ai = createAIClient(provider, user, config.corsProxy); return await ai.get(`/credits/payments/${paymentId}`) as Payment; }, onMutate: async (paymentId: string) => { // Add this payment to the refreshing set setRefreshingPayments(prev => new Set(prev).add(paymentId)); }, onSuccess: (updatedPayment) => { // Remove from refreshing set setRefreshingPayments(prev => { const newSet = new Set(prev); newSet.delete(updatedPayment.id); return newSet; }); // Update the specific payment in the cache instead of refetching queryClient.setQueryData( ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], (oldPayments) => { if (!oldPayments) return oldPayments; return oldPayments.map(payment => payment.id === updatedPayment.id ? updatedPayment : payment ); } ); // If payment completed, refresh credits balance if (updatedPayment.status === 'completed') { queryClient.invalidateQueries({ queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); toast({ title: t('paymentCompleted'), description: t('creditsAddedToAccount', { amount: formatCurrency(updatedPayment.amount) }), }); } else if (updatedPayment.status === 'failed') { toast({ title: t('paymentFailed'), description: t('paymentFailed'), variant: 'destructive', }); } else if (updatedPayment.status === 'expired') { toast({ title: t('paymentExpired'), description: t('paymentExpiredMessage'), variant: 'destructive', }); } }, onError: (error: Error, paymentId: string) => { // Remove from refreshing set on error setRefreshingPayments(prev => { const newSet = new Set(prev); newSet.delete(paymentId); return newSet; }); const errorMessage = error?.message || t('failedToCheckPaymentStatus'); toast({ title: t('refreshFailed'), description: errorMessage, variant: 'destructive', }); }, }); // Mutation for creating gift cards const createGiftcardMutation = useMutation({ mutationFn: async (request: CreateGiftcardRequest): Promise => { const ai = createAIClient(provider, user, config.corsProxy); const response = await ai.post('/credits/giftcards', { body: request, }) as GiftcardsResponse; return response.data; }, onSuccess: (giftcards) => { toast({ title: t('giftCardCreated'), description: t('successfullyCreatedGiftCards', { count: giftcards.length }), }); // Refresh gift cards list queryClient.invalidateQueries({ queryKey: ['ai-giftcards', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); // Refresh credits balance queryClient.invalidateQueries({ queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); // Reset form setGiftcardAmount(10); setGiftcardQuantity(1); }, onError: (error: Error) => { const errorMessage = error?.message || t('failedToCreateGiftCards'); toast({ title: t('creationFailed'), description: errorMessage, variant: 'destructive', }); }, }); // Mutation for redeeming gift cards const redeemGiftcardMutation = useMutation({ mutationFn: async (request: RedeemGiftcardRequest): Promise => { const ai = createAIClient(provider, user, config.corsProxy); return await ai.post('/credits/giftcards/redeem', { body: request, }) as GiftcardRedemption; }, onSuccess: (redemption) => { toast({ title: t('giftCardRedeemed'), description: t('creditsAddedToAccount', { amount: formatCurrency(redemption.amount) }), }); // Refresh credits balance queryClient.invalidateQueries({ queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); // Reset redeem code setRedeemCode(''); }, onError: (error: Error) => { const errorMessage = error?.message || t('failedToRedeemGiftCard'); toast({ title: t('redemptionFailed'), description: errorMessage, variant: 'destructive', }); }, }); const handleAddCredits = () => { if (amount <= 0) { toast({ title: t('invalidAmount'), description: t('enterValidAmount'), variant: 'destructive', }); return; } // If we have a preview payment, use it directly if (paymentPreview) { // Manually trigger the onSuccess callback with the cached payment if (paymentPreview.method === 'stripe') { // Open Stripe checkout in new window window.open(paymentPreview.url, '_blank'); toast({ title: t('paymentInitiated'), description: t('stripeCheckoutOpened'), }); } else if (paymentPreview.method === 'lightning') { // Show Lightning payment interface setLightningInvoice(paymentPreview.url); setLightningPaymentId(paymentPreview.id); } // Refresh payments list queryClient.invalidateQueries({ queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); // Refresh credits balance queryClient.invalidateQueries({ queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); // Invalidate the preview so a new one will be fetched for the next payment queryClient.invalidateQueries({ queryKey: ['ai-payment-preview', provider.nostr ? user?.pubkey ?? '' : '', provider.id, amount, paymentMethod], }); } else { // Fallback: create a new payment if preview isn't available const request: AddCreditsRequest = { amount, method: paymentMethod, }; if (paymentMethod === 'stripe') { request.redirect_url = window.location.origin + '/settings/ai'; } addCreditsMutation.mutate(request); } }; const handleCreateGiftcard = () => { if (giftcardAmount <= 0) { toast({ title: t('invalidAmount'), description: t('enterValidAmount'), variant: 'destructive', }); return; } if (giftcardQuantity <= 0 || giftcardQuantity > 100) { toast({ title: t('invalidQuantity'), description: t('quantityBetween'), variant: 'destructive', }); return; } createGiftcardMutation.mutate({ amount: giftcardAmount, quantity: giftcardQuantity, }); }; const handleRedeemGiftcard = () => { const trimmedCode = redeemCode.trim(); if (!trimmedCode) { toast({ title: t('invalidCode'), description: t('enterGiftCardCodePrompt'), variant: 'destructive', }); return; } redeemGiftcardMutation.mutate({ code: trimmedCode }); }; const handleCopyCode = (code: string) => { // Create the full shareable URL for the gift card const url = new URL('/giftcard', window.location.origin); url.hash = new URLSearchParams({ baseURL: provider.baseURL, code: code, }).toString(); navigator.clipboard.writeText(url.toString()); setCopiedCode(code); setTimeout(() => setCopiedCode(null), 2000); }; const handlePrintGiftcards = async () => { if (!giftcards || giftcards.length === 0) return; // Filter only active (non-redeemed) gift cards const activeGiftcards = giftcards.filter(gc => !gc.redeemed); if (activeGiftcards.length === 0) { toast({ title: t('noActiveGiftCards'), description: t('noActiveGiftCardsToPrint'), variant: 'destructive', }); return; } setIsPrintingQRCodes(true); try { // Generate QR codes for all active gift cards const qrCodePromises = activeGiftcards.map(async (giftcard) => { const url = `${window.location.origin}/giftcard#baseURL=${encodeURIComponent(provider.baseURL)}&code=${encodeURIComponent(giftcard.code)}`; const qrDataUrl = await QRCode.toDataURL(url, { width: 256, margin: 2, color: { dark: '#000000', light: '#ffffff', }, }); return { ...giftcard, qrDataUrl, }; }); const giftcardsWithQR = await Promise.all(qrCodePromises); // Create a new window for printing const printWindow = window.open('', '_blank'); if (!printWindow) { throw new Error(t('failedToOpenPrintWindow')); } // Generate the print HTML const printHTML = ` Shakespeare AI Gift Cards
${giftcardsWithQR.map(gc => `
Shakespeare AI Gift Card
QR Code
${formatCurrency(gc.amount)}
${gc.code}
`).join('')}
`; printWindow.document.write(printHTML); printWindow.document.close(); // Wait for images to load before printing printWindow.onload = () => { setTimeout(() => { printWindow.print(); }, 250); }; } catch (error) { console.error('Failed to generate QR codes:', error); toast({ title: t('printFailed'), description: error instanceof Error ? error.message : t('failedToGenerateQRCodes'), variant: 'destructive', }); } finally { setIsPrintingQRCodes(false); } }; const handleDownloadCSV = () => { if (!giftcards || giftcards.length === 0) return; // Filter only active (non-redeemed) gift cards const activeGiftcards = giftcards.filter(gc => !gc.redeemed); if (activeGiftcards.length === 0) { toast({ title: t('noActiveGiftCards'), description: t('noActiveGiftCardsToDownload'), variant: 'destructive', }); return; } try { // Create CSV header const headers = ['Code', 'Amount', 'Status', 'Created Date', 'Redemption URL']; // Create CSV rows const rows = activeGiftcards.map(gc => { const url = `${window.location.origin}/giftcard#baseURL=${encodeURIComponent(provider.baseURL)}&code=${encodeURIComponent(gc.code)}`; const createdDate = gc.created_at ? new Date(gc.created_at * 1000).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : 'N/A'; return [ gc.code, Number(gc.amount).toFixed(2), gc.redeemed ? 'Redeemed' : 'Active', createdDate, url ]; }); // Combine headers and rows const csvContent = [ headers.join(','), ...rows.map(row => row.map(cell => `"${cell}"`).join(',')) ].join('\n'); // Create blob and download const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); const link = document.createElement('a'); const url = URL.createObjectURL(blob); link.setAttribute('href', url); link.setAttribute('download', `shakespeare-giftcards-${new Date().toISOString().split('T')[0]}.csv`); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); toast({ title: t('csvDownloaded'), description: t('downloadedGiftCards', { count: activeGiftcards.length }), }); } catch (error) { console.error('Failed to generate CSV:', error); toast({ title: t('downloadFailed'), description: error instanceof Error ? error.message : t('failedToGenerateCSV'), variant: 'destructive', }); } }; const formatCurrency = (amount: number) => { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2, }).format(amount); }; const formatDate = (timestamp: number) => { const date = new Date(timestamp * 1000); const now = new Date(); const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24)); if (diffDays === 0) { return new Intl.DateTimeFormat('en-US', { hour: '2-digit', minute: '2-digit', }).format(date); } else if (diffDays === 1) { return t('yesterday'); } else if (diffDays < 7) { return new Intl.DateTimeFormat('en-US', { weekday: 'short', }).format(date); } else { return new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', }).format(date); } }; const getStatusIcon = (status: Payment['status']) => { switch (status) { case 'completed': return ; case 'failed': return ; case 'expired': return ; case 'pending': default: return ; } }; return ( e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-dvh-safe max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none"> {lightningInvoice ? ( <> ) : ( <> {t('credits')} )} {/* Lightning Payment Interface */} {lightningInvoice && lightningPaymentId ? (
{ setLightningInvoice(null); setLightningPaymentId(null); }} onPaymentCompleted={() => { // Close the lightning payment view immediately setLightningInvoice(null); setLightningPaymentId(null); }} />
) : (
{/* Buy Credits Accordion */}
{t('buyCredits')}
setAmount(Number(e.target.value))} placeholder={t('enterAmount')} className="text-center text-lg font-medium" />
{PRESET_AMOUNTS.map((preset) => ( ))}
setPaymentMethod(value)} className="w-full"> {t('creditCard')} {t('lightning')}
{/* Fee display */} {paymentPreview && paymentPreview.fee > 0 && (
{t('credits')} {formatCurrency(paymentPreview.amount)}
{t('processingFee')} {formatCurrency(paymentPreview.fee)}
{t('total')} {formatCurrency(paymentPreview.total)}
)}
{/* Transaction History Accordion */}
{t('recentTransactions')}
{isLoadingPayments ? (
) : !payments || payments.length === 0 ? (

{t('noTransactionsYet')}

{t('paymentHistoryAppears')}

) : (
{payments.map((payment) => (
{getStatusIcon(payment.status)} {payment.method === 'stripe' ? t('creditCard') : t('lightning')}

{formatCurrency(payment.amount)}

{payment.fee > 0 && (

+{formatCurrency(payment.fee)}

)}
{formatDate(payment.created_at)} {payment.status === 'pending' && (
{payment.url && ( )}
)}
))}
)}
{/* Redeem Gift Card Accordion */}
{t('redeemGiftCard')}
setRedeemCode(e.target.value)} placeholder={t('enterGiftCardCode')} className="flex-1" />
{/* Create Gift Card Accordion */}
{t('createGiftCard')}
setGiftcardAmount(Number(e.target.value))} placeholder={t('enterAmount')} className="text-center" />
setGiftcardQuantity(Number(e.target.value))} placeholder={t('qty')} className="text-center" />
{PRESET_AMOUNTS.map((preset) => ( ))}
{/* Your Gift Cards Accordion */}
{t('yourGiftCards')}
{giftcards && giftcards.filter(gc => !gc.redeemed).length > 0 && (
)} {isLoadingGiftcards ? (
) : !giftcards || giftcards.length === 0 ? (

{t('noGiftCardsYet')}

{t('createGiftCardsToShare')}

) : (
{giftcards.map((giftcard) => (
{t('giftCard')} {giftcard.redeemed ? t('redeemed') : t('active')}

{formatCurrency(giftcard.amount)}

{giftcard.code}
{copiedCode === giftcard.code && (
{t('copied')}
)}
{giftcard.created_at && (
{t('created')} {formatDate(giftcard.created_at)}
)}
))}
)}
)}
); }