"use client"; import { fetchData } from '@/lib/data-service'; import { useEffect, useState } from "react"; import { useParams } from "next/navigation"; import Layout from "@/components/layout/layout"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; import { Clipboard, Truck, Package } from "lucide-react"; import { useRouter } from "next/navigation"; interface Order { orderId: string; status: string; pgpAddress: string; shippingMethod: { type: string; price: number }; products: Array<{ _id: string; productId: string; quantity: number; pricePerUnit: number; totalItemPrice: number; }>; totalPrice: number; } export default function OrderDetailsPage() { const [order, setOrder] = useState(null); const [trackingNumber, setTrackingNumber] = useState(""); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); const [productNames, setProductNames] = useState>({}); const [isPaid, setIsPaid] = useState(false); const router = useRouter(); const params = useParams(); const orderId = params?.id; const fetchProductNames = async ( productIds: string[], authToken: string ): Promise> => { const productNamesMap: Record = {}; try { const promises = productIds.map((id) => fetchData(`${process.env.NEXT_PUBLIC_API_URL}/products/${id}`, { method: "GET", headers: { Authorization: `Bearer ${authToken}` }, }) ); const responses = await Promise.all(promises); const results = await Promise.all(responses.map((res) => res)); results.forEach((product, index) => { productNamesMap[productIds[index]] = product.name || "Unknown Product"; }); } catch (err) { console.error("Failed to fetch product names:", err); } return productNamesMap; }; const handleMarkAsPaid = async () => { try { const authToken = document.cookie.split("Authorization=")[1]; const response = await fetchData( `${process.env.NEXT_PUBLIC_API_URL}/orders/${orderId}`, { method: "PUT", headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}`, }, body: JSON.stringify({ status: "paid" }), } ); if (response && response.message === "Order status updated successfully") { setIsPaid(true); // Update isPaid state setOrder((prevOrder) => (prevOrder ? { ...prevOrder, status: "paid" } : null)); // Update order status console.log("Order marked as paid successfully."); } else { const errorData = await response.json(); console.error("Failed to mark order as paid:", errorData.message); alert(`Error: ${errorData.message}`); } } catch (error: any) { console.error("An error occurred while marking the order as paid:", error.message); alert("An unexpected error occurred. Please try again."); } }; useEffect(() => { const fetchOrderDetails = async () => { try { if (!orderId) return; const authToken = document.cookie.split("Authorization=")[1]; const res = await fetchData( `${process.env.NEXT_PUBLIC_API_URL}/orders/${orderId}`, { method: "GET", headers: { Authorization: `Bearer ${authToken}` }, } ); if (!res) throw new Error("Failed to fetch order details"); const data: Order = await res; setOrder(data); const productIds = data.products.map((product) => product.productId); const productNamesMap = await fetchProductNames(productIds, authToken); setProductNames(productNamesMap); if (data.status === "paid") { setIsPaid(true); } } catch (err: any) { router.push("/dashboard/orders"); setError(err.message); } finally { setLoading(false); } }; fetchOrderDetails(); }, [orderId]); const handleAddTracking = async () => { if (!trackingNumber) return; try { const authToken = document.cookie.split("Authorization=")[1]; const res = await fetchData( `${process.env.NEXT_PUBLIC_API_URL}/orders/${orderId}/tracking`, { method: "PUT", headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}`, }, body: JSON.stringify({ trackingNumber }), } ); if (!res.ok) throw new Error("Failed to update tracking number"); console.log("Tracking number updated successfully!"); } catch (err: any) { console.error(err.message); } }; const copyToClipboard = (text: string) => { navigator.clipboard.writeText(text); }; if (loading) return
Loading order details...
; if (error) return
Error: {error}
; return (

Order Details: {order?.orderId}

{order?.status}
PGP Encrypted Address Securely encrypted delivery address