"use client"; import { useQueryClient } from "@tanstack/react-query"; import { Loader2, RefreshCw } from "lucide-react"; import { useState } from "react"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; interface ChangePaymentMethodButtonProps { intentionId: number; currentPaymentMethod: string; availableMethods: string[]; canChange: boolean; } function getPaymentMethodLabel(method: string): string { switch (method) { case "pix": return "PIX"; case "tibia_coins": return "Tibia Coins"; case "gold_coins": return "Gold Coins"; case "trade": return "Troca"; default: return method.toUpperCase(); } } export function ChangePaymentMethodButton({ intentionId, currentPaymentMethod, availableMethods, canChange, }: ChangePaymentMethodButtonProps) { const [open, setOpen] = useState(false); const [selectedMethod, setSelectedMethod] = useState(currentPaymentMethod); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const queryClient = useQueryClient(); // Filtrar métodos disponíveis (excluir o atual) const availableOptions = availableMethods.filter( (method) => method !== currentPaymentMethod, ); const handleChange = async () => { if (selectedMethod === currentPaymentMethod) { setError("Selecione um método de pagamento diferente do atual"); return; } setLoading(true); setError(null); try { const res = await fetch( `/api/purchase-intentions/${intentionId}/payment-method`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ payment_method: selectedMethod }), }, ); const data = await res.json(); if (!res.ok || !data.success) { throw new Error(data.error || "Erro ao trocar método de pagamento"); } // Invalidar cache para atualizar a lista queryClient.invalidateQueries({ queryKey: ["my-purchase-intentions"] }); queryClient.invalidateQueries({ queryKey: ["purchase-intentions"] }); queryClient.invalidateQueries({ queryKey: ["listings"] }); setOpen(false); // Opcional: mostrar toast de sucesso } catch (err) { setError( err instanceof Error ? err.message : "Erro ao trocar método de pagamento", ); } finally { setLoading(false); } }; if (!canChange || availableOptions.length === 0) { return null; } return ( <> Trocar Método de Pagamento Você pode trocar o método de pagamento apenas uma vez. Escolha o novo método:
{getPaymentMethodLabel(currentPaymentMethod)}
{error && (
{error}
)}
); }