'use client' import { useState, useEffect, useCallback } from 'react' import { useRouter } from 'next/navigation' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' import { Separator } from '@/components/ui/separator' import { Package, Truck, CheckCircle, XCircle, Clock, ArrowLeft, CreditCard } from 'lucide-react' import { motion } from 'framer-motion' import Link from 'next/link' import Image from 'next/image' import { toast } from 'sonner' interface Order { id: string total: number status: 'PENDING' | 'PAID' | 'SHIPPED' | 'DELIVERED' | 'CANCELLED' createdAt: string orderItems: { id: string quantity: number price: number product: { id: string name: string images: string[] discount: number } }[] } const statusConfig = { PENDING: { label: 'Pending', color: 'bg-gradient-to-r from-yellow-400 to-orange-500', icon: Clock }, PAID: { label: 'Paid', color: 'bg-gradient-to-r from-blue-500 to-indigo-600', icon: CreditCard }, SHIPPED: { label: 'Shipped', color: 'bg-gradient-to-r from-purple-500 to-pink-600', icon: Truck }, DELIVERED: { label: 'Delivered', color: 'bg-gradient-to-r from-green-500 to-emerald-600', icon: CheckCircle }, CANCELLED: { label: 'Cancelled', color: 'bg-gradient-to-r from-red-500 to-pink-600', icon: XCircle } } export default function OrdersPage() { const router = useRouter() const [orders, setOrders] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const fetchOrders = useCallback(async () => { try { setLoading(true) setError(null) const response = await fetch('/api/orders') if (!response.ok) { if (response.status === 401) { router.push('/auth/signin?callbackUrl=/orders') return } throw new Error('Failed to fetch orders') } const data = await response.json() setOrders(data) } catch (error) { console.error('Error fetching orders:', error) setError('Failed to load orders. Please try again.') } finally { setLoading(false) } }, [router]) useEffect(() => { fetchOrders() }, [fetchOrders]) const handleCancelOrder = async (orderId: string) => { try { const response = await fetch(`/api/orders/${orderId}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status: 'CANCELLED' }) }) if (!response.ok) { throw new Error('Failed to cancel order') } toast.success('Order cancelled successfully') fetchOrders() // Refresh orders } catch (error) { console.error('Error cancelling order:', error) toast.error('Failed to cancel order') } } const handleReorder = (order: Order) => { // Add all items from this order to cart order.orderItems.forEach(item => { // This would need the full product data to add to cart console.log('Reordering:', item.product.name) }) toast.success('Items added to cart!') router.push('/checkout') } if (loading) { return (
) } if (error) { return (

Error Loading Orders

{error}

) } return (

My Orders

Track and manage your orders

{orders.length === 0 ? (

No orders yet

Start shopping to see your orders here

) : (
{orders.map((order, index) => { const StatusIcon = statusConfig[order.status].icon return (
Order #{order.id.slice(-8)}

{new Date(order.createdAt).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' })}

{statusConfig[order.status].label}
{order.orderItems.map((item) => (
{item.product.name}

{item.product.name}

Quantity: {item.quantity} × ₹{item.price.toFixed(2)}

₹{(item.price * item.quantity).toFixed(2)}

))}
Total Amount ₹{order.total.toFixed(2)}
{order.status === 'DELIVERED' && ( )} {order.status === 'PENDING' && ( )}
) })}
)}
) }