'use client'; import React, { useEffect, useState } from 'react'; import { getOrders, cancelOrder } from '../utils/orderApi'; import Link from 'next/link'; import './orders.scss'; interface OrderItem { id: number; product_id: number; product_name: string; price: number; quantity: number; total_price: number; } interface Order { id: number; order_number: string; status: string; total_amount: number; createdAt: string; shipping_address: string; shipping_city: string; shipping_postal_code: string; shipping_country: string; payment_method: string; payment_status: string; tracking_number?: string; estimated_delivery_date?: string; items: OrderItem[]; } const OrdersPage = () => { const [orders, setOrders] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchOrders = async () => { try { setLoading(true); const response = await getOrders(); setOrders(response || []); } catch (err) { console.error('Error fetching orders:', err); setError('Failed to load orders. Please try again later.'); } finally { setLoading(false); } }; fetchOrders(); }, []); const handleCancelOrder = async (orderId: number) => { if (confirm('Are you sure you want to cancel this order?')) { try { setLoading(true); await cancelOrder(orderId); setOrders(prevOrders => prevOrders.map(order => order.id === orderId ? { ...order, status: 'cancelled' } : order ) ); } catch (err) { console.error('Error cancelling order:', err); alert('Failed to cancel the order. Please try again.'); } finally { setLoading(false); } } }; const getStatusBadgeClass = (status: string) => { switch (status.toLowerCase()) { case 'pending': return 'bg-warning'; case 'processing': return 'bg-info'; case 'shipped': return 'bg-primary'; case 'delivered': return 'bg-success'; case 'cancelled': return 'bg-danger'; default: return 'bg-secondary'; } }; const formatPrice = (price: any): string => { try { const numValue = typeof price === 'string' ? parseFloat(price) : Number(price); return numValue.toFixed(2); } catch (error) { console.error("Error formatting price:", error); return "0.00"; } }; if (loading) { return (
Loading...
); } if (error) { return (
{error}
); } return (

My Orders

Track and manage your purchases

{orders.length > 0 ? (
{orders.map((order) => (
Order #{order.order_number}

{new Date(order.createdAt).toLocaleDateString()}

{order.status.charAt(0).toUpperCase() + order.status.slice(1)}
{order.items.slice(0, 3).map((item) => (
{item.product_name}
${formatPrice(item.price)} x {item.quantity} ${formatPrice(item.total_price)}
))} {order.items.length > 3 && (
+{order.items.length - 3} more items
)}
Total: ${formatPrice(order.total_amount)}
View Details {order.status === 'pending' && ( )}
))}
) : (

You haven't placed any orders yet

When you place an order, it will appear here for you to track

Start Shopping Now
)}
); }; export default OrdersPage;