'use client' import React, { useState, useEffect } from 'react' import { useAuth } from '@/contexts/AuthContext' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select' import { Alert, AlertDescription } from '@/components/ui/alert' import { Wallet, Plus, RefreshCw, CreditCard } from 'lucide-react' import { useToast } from '@/hooks/use-toast' interface BalanceCardProps { showAddBalance?: boolean className?: string } export function BalanceCard({ showAddBalance = true, className = '' }: BalanceCardProps) { const { user, getBalance, addBalance, refreshBalance } = useAuth() const { toast } = useToast() const [balance, setBalance] = useState(user?.balance || 0) const [loading, setLoading] = useState(false) const [refreshing, setRefreshing] = useState(false) const [showAddForm, setShowAddForm] = useState(false) const [amount, setAmount] = useState('') const [currency, setCurrency] = useState<'INR' | 'USD'>('INR') const [error, setError] = useState(null) // Update balance when user changes useEffect(() => { if (user?.balance !== undefined) { setBalance(user.balance) } }, [user?.balance]) const handleRefreshBalance = async () => { if (!user) return setRefreshing(true) setError(null) try { const newBalance = await getBalance() setBalance(newBalance) await refreshBalance() // Update user context toast({ title: 'Balance Updated', description: 'Your balance has been refreshed successfully.', }) } catch (err) { const errorMessage = err instanceof Error ? err.message : 'Failed to refresh balance' setError(errorMessage) toast({ title: 'Error', description: errorMessage, variant: 'destructive', }) } finally { setRefreshing(false) } } const handleAddBalance = async (e: React.FormEvent) => { e.preventDefault() const numAmount = parseFloat(amount) if (!numAmount || numAmount <= 0) { setError('Please enter a valid amount') return } const minAmount = currency === 'INR' ? 100 : 2 const maxAmount = currency === 'INR' ? 100000 : 1500 if (numAmount < minAmount || numAmount > maxAmount) { setError( `Amount must be between ${currency === 'INR' ? '₹' : '$'}${minAmount} and ${currency === 'INR' ? '₹' : '$'}${maxAmount}` ) return } setLoading(true) setError(null) try { const result = await addBalance(numAmount, currency) if (result.success && result.paymentUrl && result.formData) { // Create and submit payment form const form = document.createElement('form') form.method = 'POST' form.action = result.paymentUrl form.style.display = 'none' // Add form data Object.entries(result.formData).forEach(([key, value]) => { const input = document.createElement('input') input.type = 'hidden' input.name = key input.value = String(value) form.appendChild(input) }) document.body.appendChild(form) form.submit() toast({ title: 'Redirecting to Payment', description: 'You will be redirected to the payment gateway.', }) } else { setError(result.error || 'Failed to initiate payment') toast({ title: 'Payment Error', description: result.error || 'Failed to initiate payment', variant: 'destructive', }) } } catch (err) { const errorMessage = err instanceof Error ? err.message : 'Failed to add balance' setError(errorMessage) toast({ title: 'Error', description: errorMessage, variant: 'destructive', }) } finally { setLoading(false) } } const formatBalance = (amount: number) => { return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', minimumFractionDigits: 0, maximumFractionDigits: 2, }).format(amount) } if (!user) { return null } return (
Balance
{formatBalance(balance)}
Available Balance
{error && ( {error} )} {showAddBalance && (
{!showAddForm ? ( ) : (
setAmount(e.target.value)} min={currency === 'INR' ? 100 : 2} max={currency === 'INR' ? 100000 : 1500} step={currency === 'INR' ? 1 : 0.01} required />
Min: {currency === 'INR' ? '₹100' : '$2'} | Max:{' '} {currency === 'INR' ? '₹1,00,000' : '$1,500'}
)}
)}
) }