Files
pagodera/components/purchase-intentions/ChangePaymentMethodButton.tsx
2025-11-11 03:08:36 -03:00

194 lines
5.3 KiB
TypeScript

"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<string>(currentPaymentMethod);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(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 (
<>
<Button
variant="outline"
size="sm"
onClick={() => {
setOpen(true);
setSelectedMethod(currentPaymentMethod);
setError(null);
}}
className="gap-2"
>
<RefreshCw className="h-4 w-4" />
Trocar Método
</Button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Trocar Método de Pagamento</DialogTitle>
<DialogDescription>
Você pode trocar o método de pagamento apenas uma vez. Escolha o
novo método:
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label>Método Atual</Label>
<div className="text-sm text-muted-foreground p-2 bg-muted rounded-md">
{getPaymentMethodLabel(currentPaymentMethod)}
</div>
</div>
<div className="space-y-2">
<Label htmlFor="new-method">Novo Método de Pagamento</Label>
<Select value={selectedMethod} onValueChange={setSelectedMethod}>
<SelectTrigger id="new-method">
<SelectValue placeholder="Selecione um método" />
</SelectTrigger>
<SelectContent>
{availableOptions.map((method) => (
<SelectItem key={method} value={method}>
{getPaymentMethodLabel(method)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{error && (
<div className="bg-destructive/10 text-destructive p-3 rounded-lg text-sm">
{error}
</div>
)}
<div className="flex gap-2 justify-end">
<Button
variant="outline"
onClick={() => setOpen(false)}
disabled={loading}
>
Cancelar
</Button>
<Button
onClick={handleChange}
disabled={loading || selectedMethod === currentPaymentMethod}
>
{loading ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Trocando...
</>
) : (
"Confirmar Troca"
)}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</>
);
}