import { useState } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle } from 'lucide-react'; 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 { Separator } from '@/components/ui/separator'; import { Skeleton } from '@/components/ui/skeleton'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { useToast } from '@/hooks/useToast'; import { createAIClient } from '@/lib/ai-client'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import type { AIConnection } from '@/contexts/AISettingsContext'; interface CreditsDialogProps { open: boolean; onOpenChange: (open: boolean) => void; providerId: string; connection: AIConnection; } 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; } const PRESET_AMOUNTS = [5, 10, 25, 50, 100]; export function CreditsDialog({ open, onOpenChange, providerId, connection }: CreditsDialogProps) { const { user } = useCurrentUser(); const { toast } = useToast(); const queryClient = useQueryClient(); const [amount, setAmount] = useState(10); const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe'); // Query for payment history const { data: payments, isLoading: isLoadingPayments } = useQuery({ queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId], queryFn: async (): Promise => { const ai = createAIClient(connection, user); const data = await ai.get('/credits/payments?limit=50') as PaymentsResponse; return data.data; }, enabled: open && !!user, retry: false, refetchOnWindowFocus: false, }); // Mutation for adding credits const addCreditsMutation = useMutation({ mutationFn: async (request: AddCreditsRequest): Promise => { const ai = createAIClient(connection, user); 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: 'Payment initiated', description: 'Stripe checkout opened in a new window.', }); } else if (payment.method === 'lightning') { // Copy Lightning invoice to clipboard navigator.clipboard.writeText(payment.url); toast({ title: 'Lightning invoice copied', description: 'The Lightning invoice has been copied to your clipboard.', }); } // Refresh payments list queryClient.invalidateQueries({ queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId], }); // Refresh credits balance queryClient.invalidateQueries({ queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId], }); }, onError: (error: Error) => { const errorMessage = error?.message || 'Failed to initiate payment'; toast({ title: 'Payment failed', description: errorMessage, variant: 'destructive', }); }, }); const handleAddCredits = () => { if (!user) { toast({ title: 'Authentication required', description: 'Please log in to purchase credits.', variant: 'destructive', }); return; } if (amount <= 0) { toast({ title: 'Invalid amount', description: 'Please enter a valid amount.', variant: 'destructive', }); return; } const request: AddCreditsRequest = { amount, method: paymentMethod, }; if (paymentMethod === 'stripe') { request.redirect_url = window.location.origin + '/settings/ai'; } addCreditsMutation.mutate(request); }; 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 '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 ; } }; const getStatusVariant = (status: Payment['status']): "default" | "secondary" | "destructive" | "outline" => { switch (status) { case 'completed': return 'default'; case 'failed': return 'destructive'; case 'expired': return 'secondary'; case 'pending': default: return 'outline'; } }; return ( Credits
{/* Add Credits Form */}
setAmount(Number(e.target.value))} placeholder="Enter amount" className="text-center text-lg font-medium" />
{PRESET_AMOUNTS.map((preset) => ( ))}
{!user && (

Please log in to purchase credits

)}
{/* Transaction History */}

Recent Transactions

{isLoadingPayments ? (
{Array.from({ length: 3 }).map((_, i) => (
))}
) : !payments || payments.length === 0 ? (

No transactions yet

Your payment history will appear here

) : (
{payments.slice(0, 5).map((payment) => (
{getStatusIcon(payment.status)} {payment.method === 'stripe' ? 'Credit Card' : 'Lightning'} {payment.status}

{formatCurrency(payment.amount)}

{payment.fee > 0 && (

+{formatCurrency(payment.fee)}

)}
{formatDate(payment.created_at)} {payment.status === 'pending' && payment.url && ( )}
))} {payments.length > 5 && (

Showing recent 5 transactions

)}
)}
); }