"use client"; import { useState } from "react"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { TransferCoinsSchema, type TransferCoinsInput } from "@/lib/schemas"; import { transferCoins } from "@/lib/actions/user"; import { useToast } from "@/hooks/use-toast"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose, } from "@/components/ui/dialog"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, FormDescription, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { Loader2, Send, Coins } from "lucide-react"; interface TransferCoinsDialogProps { isOpen: boolean; onOpenChange: (isOpen: boolean) => void; currentUserCoins: number; onTransferSuccess: (newBalance: number) => void; } export function TransferCoinsDialog({ isOpen, onOpenChange, currentUserCoins, onTransferSuccess, }: TransferCoinsDialogProps) { const { toast } = useToast(); const [isLoading, setIsLoading] = useState(false); const form = useForm({ resolver: zodResolver(TransferCoinsSchema), defaultValues: { recipientEmail: "", amount: 0, }, }); async function onSubmit(values: TransferCoinsInput) { setIsLoading(true); try { const result = await transferCoins(values); toast({ title: result.success ? "Transfer Successful!" : "Transfer Failed", description: result.message, variant: result.success ? "default" : "destructive", }); if (result.success && result.newSenderBalance !== undefined) { onTransferSuccess(result.newSenderBalance); form.reset(); onOpenChange(false); // Close dialog on success } } catch (error) { toast({ title: "Error", description: "An unexpected error occurred. Please try again.", variant: "destructive", }); } finally { setIsLoading(false); } } return ( { if (!isLoading) { // Prevent closing while submitting onOpenChange(open); if (!open) form.reset(); // Reset form if dialog is closed } }}> Transfer Coins Send coins to another user. Make sure the recipient's email is correct.
Your current balance: {currentUserCoins.toLocaleString()} Coins
( Recipient's Email )} /> ( Amount to Transfer field.onChange(parseInt(e.target.value, 10) || 0)} /> Enter a whole number of coins to transfer. )} />
); }