"use client"; import React, { useState, useEffect } from "react"; import { Package, ShoppingBag, Info, ExternalLink } from "lucide-react"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; import { getCookie } from "@/lib/client-utils"; import axios from "axios"; import { useRouter } from "next/navigation"; interface Order { _id: string; orderId: number; status: string; totalPrice: number; orderDate: string; products: Array<{ productId: string; quantity: number; pricePerUnit: number; totalItemPrice: number; }>; } interface BuyerOrderInfoProps { buyerId: string; } export default function BuyerOrderInfo({ buyerId }: BuyerOrderInfoProps) { const router = useRouter(); const [loading, setLoading] = useState(true); const [orders, setOrders] = useState([]); useEffect(() => { // Only load if we have a buyerId if (!buyerId) return; const fetchBuyerOrders = async () => { try { const authToken = getCookie("Authorization"); if (!authToken) return; const authAxios = axios.create({ baseURL: process.env.NEXT_PUBLIC_API_URL, headers: { Authorization: `Bearer ${authToken}` } }); // Fetch orders for this specific buyer const response = await authAxios.get(`/orders/buyer/${buyerId}?limit=5`); if (response.data && response.data.orders) { setOrders(response.data.orders); } setLoading(false); } catch (error) { console.error("Error fetching buyer orders:", error); setLoading(false); } }; fetchBuyerOrders(); }, [buyerId]); const handleViewOrder = (orderId: string) => { router.push(`/dashboard/orders/${orderId}`); }; // Format the price as currency const formatPrice = (price: number) => { return `£${price.toFixed(2)}`; }; // Don't show anything while loading or if no orders if (loading || orders.length === 0) { return null; } // Count products across all orders const productCount = orders.reduce((total, order) => { return total + order.products.reduce((sum, product) => sum + product.quantity, 0); }, 0); return (
Recent Orders from this Customer
{orders.map((order) => (
handleViewOrder(order._id)} >
Order #{order.orderId}
{order.status.toUpperCase()}
{order.products.length} {order.products.length === 1 ? 'product' : 'products'} · {formatPrice(order.totalPrice)}
{new Date(order.orderDate).toLocaleDateString()}
))}
); }