409 lines
12 KiB
TypeScript
409 lines
12 KiB
TypeScript
"use client";
|
|
|
|
import { Loader2, TrendingUp } from "lucide-react";
|
|
import { useEffect, useState } from "react";
|
|
import { Badge } from "@/components/ui/badge";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "@/components/ui/dialog";
|
|
import { Input } from "@/components/ui/input";
|
|
import { Label } from "@/components/ui/label";
|
|
import {
|
|
Select,
|
|
SelectContent,
|
|
SelectItem,
|
|
SelectTrigger,
|
|
SelectValue,
|
|
} from "@/components/ui/select";
|
|
import { Separator } from "@/components/ui/separator";
|
|
import { useSession } from "@/lib/hooks/use-session";
|
|
|
|
interface Listing {
|
|
listing_id: number;
|
|
item_name: string;
|
|
quantity: number;
|
|
current_bid_amount: number | null;
|
|
min_bid_increment: number | null;
|
|
initial_price_pix: number | null;
|
|
initial_price_tibia_coins: number | null;
|
|
initial_price_gold_coins: number | null;
|
|
price_pix: number | null;
|
|
price_tibia_coins: number | null;
|
|
price_gold_coins: number | null;
|
|
auction_ends_at: Date | null;
|
|
}
|
|
|
|
interface BidModalProps {
|
|
open: boolean;
|
|
onOpenChange: (open: boolean) => void;
|
|
listing: Listing | null;
|
|
onSuccess?: () => void;
|
|
}
|
|
|
|
export function BidModal({
|
|
open,
|
|
onOpenChange,
|
|
listing,
|
|
onSuccess,
|
|
}: BidModalProps) {
|
|
const { user } = useSession();
|
|
const [bidAmount, setBidAmount] = useState<string>("");
|
|
const [paymentMethod, setPaymentMethod] = useState<string>("");
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [bidHistory, setBidHistory] = useState<
|
|
Array<{
|
|
bid_id: number;
|
|
bidder_id: number;
|
|
bidder_name: string;
|
|
bid_amount: number;
|
|
bid_type: string | null;
|
|
created_at: Date;
|
|
}>
|
|
>([]);
|
|
const [loadingHistory, setLoadingHistory] = useState(false);
|
|
|
|
if (!listing) return null;
|
|
|
|
// Calcular valores
|
|
const currentBid = listing.current_bid_amount || 0;
|
|
const minIncrement = listing.min_bid_increment || 10;
|
|
const minBid = currentBid + minIncrement;
|
|
const initialPrice =
|
|
listing.initial_price_pix ||
|
|
listing.initial_price_tibia_coins ||
|
|
listing.initial_price_gold_coins ||
|
|
0;
|
|
|
|
// Determinar métodos de pagamento disponíveis para lance
|
|
const availableMethods: string[] = [];
|
|
if (listing.price_pix || listing.initial_price_pix)
|
|
availableMethods.push("pix");
|
|
if (listing.price_tibia_coins || listing.initial_price_tibia_coins)
|
|
availableMethods.push("tc");
|
|
if (listing.price_gold_coins || listing.initial_price_gold_coins)
|
|
availableMethods.push("gp");
|
|
|
|
// Selecionar primeiro método disponível por padrão
|
|
useEffect(() => {
|
|
if (availableMethods.length > 0 && !paymentMethod) {
|
|
setPaymentMethod(availableMethods[0]);
|
|
}
|
|
}, [paymentMethod]);
|
|
|
|
// Atualizar valor do lance quando mudar
|
|
useEffect(() => {
|
|
if (bidAmount === "" && minBid > 0) {
|
|
setBidAmount(minBid.toFixed(2));
|
|
}
|
|
}, [minBid, bidAmount]);
|
|
|
|
// Buscar histórico de lances quando abrir modal
|
|
useEffect(() => {
|
|
if (open && listing) {
|
|
fetchBidHistory();
|
|
}
|
|
}, [open, listing?.listing_id, fetchBidHistory, listing]);
|
|
|
|
const fetchBidHistory = async () => {
|
|
if (!listing) return;
|
|
|
|
setLoadingHistory(true);
|
|
try {
|
|
const res = await fetch(
|
|
`/api/listings/${listing.listing_id}/bids?limit=5`,
|
|
);
|
|
if (res.ok) {
|
|
const data = await res.json();
|
|
if (data.success) {
|
|
setBidHistory(data.bids || []);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error("Erro ao buscar histórico de lances:", error);
|
|
} finally {
|
|
setLoadingHistory(false);
|
|
}
|
|
};
|
|
|
|
const handleBid = async () => {
|
|
const amount = parseFloat(bidAmount);
|
|
|
|
if (Number.isNaN(amount) || amount <= 0) {
|
|
setError("Valor do lance inválido");
|
|
return;
|
|
}
|
|
|
|
if (amount < minBid) {
|
|
setError(
|
|
`Lance mínimo é ${minBid.toFixed(2)} (lance atual: ${currentBid.toFixed(2)} + incremento: ${minIncrement.toFixed(2)})`,
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (!paymentMethod) {
|
|
setError("Selecione um método de pagamento");
|
|
return;
|
|
}
|
|
|
|
setLoading(true);
|
|
setError(null);
|
|
|
|
try {
|
|
const response = await fetch(`/api/listings/${listing.listing_id}/bid`, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
amount,
|
|
payment_method: paymentMethod,
|
|
}),
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (!response.ok || !data.success) {
|
|
throw new Error(data.error || "Erro ao processar lance");
|
|
}
|
|
|
|
// Sucesso - atualizar histórico
|
|
await fetchBidHistory();
|
|
if (onSuccess) {
|
|
onSuccess();
|
|
}
|
|
onOpenChange(false);
|
|
setBidAmount("");
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : "Erro ao processar lance");
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const formatPrice = (price: number | null) => {
|
|
if (!price) return "N/A";
|
|
return `R$ ${price.toFixed(2)}`;
|
|
};
|
|
|
|
return (
|
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-[500px]">
|
|
<DialogHeader>
|
|
<DialogTitle>Dar Lance</DialogTitle>
|
|
<DialogDescription>
|
|
Informe o valor do seu lance para este leilão
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<div className="space-y-4">
|
|
{/* Resumo do item */}
|
|
<div className="bg-muted p-4 rounded-lg">
|
|
<h3 className="font-semibold mb-2">{listing.item_name}</h3>
|
|
<p className="text-sm text-muted-foreground">
|
|
Quantidade: {listing.quantity}
|
|
</p>
|
|
</div>
|
|
|
|
<Separator />
|
|
|
|
{/* Informações do leilão */}
|
|
<div className="space-y-3">
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div>
|
|
<Label className="text-xs text-muted-foreground">
|
|
Preço Inicial
|
|
</Label>
|
|
<p className="text-lg font-semibold">
|
|
{formatPrice(initialPrice)}
|
|
</p>
|
|
</div>
|
|
<div>
|
|
<Label className="text-xs text-muted-foreground">
|
|
Lance Atual
|
|
</Label>
|
|
<p className="text-lg font-semibold text-primary">
|
|
{currentBid > 0 ? formatPrice(currentBid) : "Sem lances"}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div>
|
|
<Label className="text-xs text-muted-foreground">
|
|
Incremento Mínimo
|
|
</Label>
|
|
<p className="text-sm font-medium">
|
|
{formatPrice(minIncrement)}
|
|
</p>
|
|
</div>
|
|
<div>
|
|
<Label className="text-xs text-muted-foreground">
|
|
Lance Mínimo Necessário
|
|
</Label>
|
|
<p className="text-sm font-semibold text-green-600">
|
|
{formatPrice(minBid)}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
{listing.auction_ends_at && (
|
|
<div>
|
|
<Label className="text-xs text-muted-foreground">
|
|
Término do Leilão
|
|
</Label>
|
|
<p className="text-sm">
|
|
{new Date(listing.auction_ends_at).toLocaleString("pt-BR")}
|
|
</p>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<Separator />
|
|
|
|
{/* Histórico de lances */}
|
|
{bidHistory.length > 0 && (
|
|
<div className="space-y-2">
|
|
<Label className="text-sm font-medium">
|
|
Histórico de Lances (Últimos 5)
|
|
</Label>
|
|
<div className="bg-muted rounded-lg p-3 space-y-2 max-h-48 overflow-y-auto">
|
|
{bidHistory.map((bid, index) => {
|
|
const isCurrentUser = user?.userId === bid.bidder_id;
|
|
const isHighest = index === 0;
|
|
return (
|
|
<div
|
|
key={bid.bid_id}
|
|
className={`p-2 rounded ${
|
|
isCurrentUser
|
|
? "bg-primary/10 border border-primary/20"
|
|
: ""
|
|
} ${isHighest ? "border-l-2 border-l-primary" : ""}`}
|
|
>
|
|
<div className="flex items-center justify-between">
|
|
<div className="flex-1">
|
|
<div className="flex items-center gap-2">
|
|
<span className="font-medium text-sm">
|
|
{isCurrentUser ? "Você" : bid.bidder_name}
|
|
</span>
|
|
{isHighest && (
|
|
<Badge variant="secondary" className="text-xs">
|
|
Líder
|
|
</Badge>
|
|
)}
|
|
{isCurrentUser && (
|
|
<Badge variant="outline" className="text-xs">
|
|
Seu lance
|
|
</Badge>
|
|
)}
|
|
</div>
|
|
<p className="text-xs text-muted-foreground">
|
|
{new Date(bid.created_at).toLocaleString("pt-BR")}
|
|
</p>
|
|
</div>
|
|
<span className="font-semibold text-primary">
|
|
R$ {bid.bid_amount.toFixed(2)}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{loadingHistory && (
|
|
<div className="text-center text-sm text-muted-foreground py-4">
|
|
Carregando histórico...
|
|
</div>
|
|
)}
|
|
|
|
<Separator />
|
|
|
|
{/* Input do lance */}
|
|
<div className="space-y-2">
|
|
<Label htmlFor="bid-amount">Valor do Lance (R$)</Label>
|
|
<Input
|
|
id="bid-amount"
|
|
type="number"
|
|
step="0.01"
|
|
min={minBid}
|
|
value={bidAmount}
|
|
onChange={(e) => setBidAmount(e.target.value)}
|
|
placeholder={minBid.toFixed(2)}
|
|
className="text-lg"
|
|
/>
|
|
<p className="text-xs text-muted-foreground">
|
|
Valor mínimo: {formatPrice(minBid)}
|
|
</p>
|
|
</div>
|
|
|
|
{/* Seleção de método de pagamento */}
|
|
{availableMethods.length > 0 && (
|
|
<div className="space-y-2">
|
|
<Label htmlFor="payment-method">Método de Pagamento</Label>
|
|
<Select value={paymentMethod} onValueChange={setPaymentMethod}>
|
|
<SelectTrigger id="payment-method">
|
|
<SelectValue placeholder="Selecione o método" />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{availableMethods.map((method) => (
|
|
<SelectItem key={method} value={method}>
|
|
{method.toUpperCase()}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
)}
|
|
|
|
{error && (
|
|
<div className="bg-destructive/10 text-destructive p-3 rounded-lg text-sm">
|
|
{error}
|
|
</div>
|
|
)}
|
|
|
|
<Separator />
|
|
|
|
{/* Botões */}
|
|
<div className="flex gap-2 justify-end">
|
|
<Button
|
|
variant="outline"
|
|
onClick={() => onOpenChange(false)}
|
|
disabled={loading}
|
|
>
|
|
Cancelar
|
|
</Button>
|
|
<Button
|
|
onClick={handleBid}
|
|
disabled={
|
|
loading ||
|
|
!bidAmount ||
|
|
parseFloat(bidAmount) < minBid ||
|
|
!paymentMethod
|
|
}
|
|
>
|
|
{loading ? (
|
|
<>
|
|
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
|
Processando...
|
|
</>
|
|
) : (
|
|
<>
|
|
<TrendingUp className="h-4 w-4 mr-2" />
|
|
Confirmar Lance
|
|
</>
|
|
)}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|