"use client"; import { useState } from "react"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { Skeleton } from "@/components/ui/skeleton"; import { Card, CardContent, CardHeader } from "@/components/ui/card"; import { Clock, CheckCircle2, XCircle, MessageSquare, ShoppingCart, MapPin, Package, User, ExternalLink, AlertCircle, DollarSign, Coins, RefreshCw, } from "lucide-react"; import { useMyPurchaseIntentions, type PurchaseIntention, type PurchaseIntentionStatus } from "@/lib/hooks/use-purchase-intentions"; import { useSession } from "@/lib/hooks/use-session"; import Link from "next/link"; import Image from "next/image"; import { cn } from "@/lib/utils"; import { ChangePaymentMethodButton } from "@/components/purchase-intentions/ChangePaymentMethodButton"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { ChatModal } from "@/components/chat/ChatModal"; function formatTimeAgo(date: Date | string): string { const dateObj = typeof date === "string" ? new Date(date) : date; const seconds = Math.floor((new Date().getTime() - dateObj.getTime()) / 1000); if (seconds < 60) return "há alguns segundos"; const minutes = Math.floor(seconds / 60); if (minutes < 60) return `há ${minutes} ${minutes === 1 ? "minuto" : "minutos"}`; const hours = Math.floor(minutes / 60); if (hours < 24) return `há ${hours} ${hours === 1 ? "hora" : "horas"}`; const days = Math.floor(hours / 24); if (days < 30) return `há ${days} ${days === 1 ? "dia" : "dias"}`; const months = Math.floor(days / 30); if (months < 12) return `há ${months} ${months === 1 ? "mês" : "meses"}`; const years = Math.floor(months / 12); return `há ${years} ${years === 1 ? "ano" : "anos"}`; } function getStatusBadge(status: PurchaseIntentionStatus) { switch (status) { case "pending": return ( Pendente ); case "accepted": return ( Aceita ); case "rejected": return ( Rejeitada ); case "expired": return ( Expirada ); case "completed": return ( Concluída ); default: return {status}; } } 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(); } } function formatPrice(price: number | null, method: string): string { if (price === null) return "N/A"; if (method === "pix") { return new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL", }).format(price); } if (method === "tibia_coins") { return `${price.toLocaleString("pt-BR")} TC`; } if (method === "gold_coins") { const gold = price / 1000000; if (gold >= 1) { return `${gold.toFixed(2)}kk`; } return `${price.toLocaleString("pt-BR")} gp`; } return price.toLocaleString("pt-BR"); } function formatCustomOffer(amount: number | null | undefined, currency: string | null | undefined): string | null { if (amount === null || amount === undefined || !currency) { return null; } switch (currency) { case "pix": return `R$ ${amount.toFixed(2)}`; case "tibia_coins": return `${Math.round(amount).toLocaleString("pt-BR")} TC`; case "gold_coins": return `${Math.round(amount).toLocaleString("pt-BR")} GP`; default: return amount.toLocaleString("pt-BR"); } } interface IntentionCardProps { intention: PurchaseIntention; locale?: string; } function IntentionCard({ intention, locale = "pt" }: IntentionCardProps) { const listing = intention.listing; const [showListingModal, setShowListingModal] = useState(false); const [showChatModal, setShowChatModal] = useState(false); if (!listing) { return (

Anúncio não disponível

{getStatusBadge(intention.status)}

Este anúncio foi removido ou não está mais disponível

Intenção criada {formatTimeAgo(intention.created_at)}
); } const getItemImageUrl = () => { if (listing.image_url) { return listing.image_url; } if (listing.image_local_path) { const normalizedPath = listing.image_local_path.replace(/\\/g, "/"); if (normalizedPath.startsWith("data/")) { return `/api/images?path=${encodeURIComponent(normalizedPath)}`; } const category = listing.item_category || "other"; return `/api/images?path=${encodeURIComponent(`data/images/${category}/${normalizedPath}`)}`; } if (listing.item_id_unified) { const params = new URLSearchParams({ item: listing.item_id_unified.toString() }); if (listing.item_name) { params.set("name", listing.item_name); } return `/api/images?${params.toString()}`; } const params = new URLSearchParams({ item: listing.item_id.toString() }); if (listing.item_name) { params.set("name", listing.item_name); } return `/api/images?${params.toString()}`; }; const itemImageUrl = getItemImageUrl(); const chatId = intention.chat_id ?? (listing.seller_id != null ? `${listing.listing_id}_${intention.buyer_id}_${listing.seller_id}` : null); const price = listing.price_pix && intention.payment_method === "pix" ? listing.price_pix : listing.price_tibia_coins && intention.payment_method === "tibia_coins" ? listing.price_tibia_coins : listing.price_gold_coins && intention.payment_method === "gold_coins" ? listing.price_gold_coins : null; const customOfferLabel = formatCustomOffer( typeof intention.custom_offer_amount === "number" ? intention.custom_offer_amount : null, intention.custom_offer_currency ?? null ); return ( <>
{itemImageUrl ? ( {listing.item_name} ) : ( )}

{listing.item_name}

{getStatusBadge(intention.status)}
{listing.server_name}
Qtd: {listing.quantity}
{getPaymentMethodLabel(intention.payment_method)} {price !== null && ( {formatPrice(price, intention.payment_method)} )}
{customOfferLabel && (
Sua oferta: {customOfferLabel}
)}
{/* Informações do vendedor */}
Vendedor: {listing.seller_character_name || listing.seller_username || "Desconhecido"}
{/* Mensagem do comprador */} {intention.buyer_message && (

Sua mensagem:

{intention.buyer_message}

)} {/* Resposta do vendedor */} {intention.seller_response && (

{intention.status === "accepted" ? "Resposta do vendedor (Aceita):" : intention.status === "rejected" ? "Resposta do vendedor (Rejeitada):" : "Resposta do vendedor:"}

{intention.seller_response}

)} {/* Timestamps */}
Criada {formatTimeAgo(intention.created_at)}
{intention.updated_at !== intention.created_at && ( Atualizada {formatTimeAgo(intention.updated_at)} )}
{/* Actions */}
{intention.status === "pending" && intention.payment_method_change_count < 1 && ( )} {intention.status === "accepted" && listing.listing_status === "active" && ( )}
{listing.item_name} Detalhes do anúncio selecionado
{itemImageUrl ? ( {listing.item_name} ) : ( )}

{listing.item_name}

{listing.description ?? "Sem descrição fornecida para este anúncio."}

Servidor: {listing.server_name}
Quantidade: {listing.quantity}
Vendedor:{" "} {listing.seller_character_name || listing.seller_username || "Desconhecido"}

Condições de pagamento

{listing.price_pix && ( {formatPrice(listing.price_pix, "pix")} )} {listing.price_tibia_coins && ( {formatPrice(listing.price_tibia_coins, "tibia_coins")} )} {listing.price_gold_coins && ( {formatPrice(listing.price_gold_coins, "gold_coins")} )} {listing.trade_item_id && listing.trade_item_name && listing.trade_item_quantity && ( {listing.trade_item_quantity}x {listing.trade_item_name} )}
{listing && ( )} ); } interface MyPurchaseIntentionsPanelProps { locale?: string; } export function MyPurchaseIntentionsPanel({ locale = "pt" }: MyPurchaseIntentionsPanelProps) { const { user } = useSession(); const [filter, setFilter] = useState("all"); const { intentions, isLoading } = useMyPurchaseIntentions(); // Contar por status const pendingCount = intentions.filter((i) => i.status === "pending").length; const acceptedCount = intentions.filter((i) => i.status === "accepted").length; const rejectedCount = intentions.filter((i) => i.status === "rejected").length; const expiredCount = intentions.filter((i) => i.status === "expired").length; const completedCount = intentions.filter((i) => i.status === "completed").length; const filteredIntentions = filter === "all" ? intentions : intentions.filter((intention) => intention.status === filter); if (!user) { return (

Faça login para ver suas intenções de compra

); } return (

Minhas Intenções de Compra

Acompanhe suas intenções de compra e respostas dos vendedores

{/* Filtros */}
{expiredCount > 0 && ( )} {completedCount > 0 && ( )}
{/* Lista de intenções */} {isLoading ? (
{Array.from({ length: 3 }).map((_, i) => ( ))}
) : filteredIntentions.length === 0 ? (

Nenhuma intenção de compra encontrada

{filter === "all" ? "Quando você manifestar interesse em comprar um item, ele aparecerá aqui." : `Não há intenções com status "${filter}" no momento.`}

) : (
{filteredIntentions.map((intention) => ( ))}
)}
); }