'use client' import { useState, useEffect, useCallback } from 'react' import { useParams, 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 { ArrowLeft, Package, User, CreditCard, Truck, CheckCircle, XCircle, Clock, MapPin, Phone, Mail } from 'lucide-react' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select' import { toast } from 'sonner' import { motion } from 'framer-motion' import Link from 'next/link' import Image from 'next/image' interface OrderItem { id: string quantity: number price: number product: { id: string name: string images: string[] sku: string price: number } } interface ShippingAddress { firstName: string lastName: string company?: string | null address1: string address2?: string | null city: string state: string zipCode: string country: string phone?: string | null } interface Order { id: string total: number status: 'PENDING' | 'PAID' | 'SHIPPED' | 'DELIVERED' | 'CANCELLED' createdAt: string updatedAt: string razorpayOrderId: string | null razorpayPaymentId: string | null shippingAddress: ShippingAddress | null user: { id: string name: string email: string phone: string | null } orderItems: OrderItem[] } const statusColors = { PENDING: 'bg-yellow-100 text-yellow-800 border-yellow-200', PAID: 'bg-blue-100 text-blue-800 border-blue-200', SHIPPED: 'bg-purple-100 text-purple-800 border-purple-200', DELIVERED: 'bg-green-100 text-green-800 border-green-200', CANCELLED: 'bg-red-100 text-red-800 border-red-200' } const statusIcons = { PENDING: Clock, PAID: CreditCard, SHIPPED: Truck, DELIVERED: CheckCircle, CANCELLED: XCircle } export default function AdminOrderDetail() { const params = useParams() const router = useRouter() const [order, setOrder] = useState(null) const [loading, setLoading] = useState(true) const [updating, setUpdating] = useState(false) const orderId = params.id as string const fetchOrder = useCallback(async () => { try { setLoading(true) const response = await fetch(`/api/admin/orders/${orderId}`) if (!response.ok) { throw new Error('Failed to fetch order') } const data = await response.json() setOrder(data) } catch (error) { console.error('Error fetching order:', error) toast.error('Failed to load order details') } finally { setLoading(false) } }, [orderId]) const updateOrderStatus = async (newStatus: string) => { try { setUpdating(true) const response = await fetch(`/api/admin/orders/${orderId}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ status: newStatus }), }) if (!response.ok) { throw new Error('Failed to update order status') } const data = await response.json() setOrder(data) toast.success('Order status updated successfully') } catch (error) { console.error('Error updating order:', error) toast.error('Failed to update order status') } finally { setUpdating(false) } } useEffect(() => { if (orderId) { fetchOrder() } }, [orderId, fetchOrder]) if (loading) { return (
) } if (!order) { return (

Order Not Found

The order you're looking for doesn't exist.

) } const StatusIcon = statusIcons[order.status] || Clock return ( {/* Header */}

Order #{order.id}

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

{order.status}
{/* Order Items */}
Order Items ({order.orderItems?.length || 0})
{order.orderItems && order.orderItems.length > 0 ? ( order.orderItems.map((item) => (
{item.product?.images && item.product.images.length > 0 ? ( {item.product.name ) : ( )}

{item.product?.name || 'Unknown Product'}

SKU: {item.product?.sku || 'N/A'}

Qty: {item.quantity} Price: ₹{item.price.toFixed(2)} each

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

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

)) ) : (

No items found in this order

)}
Total Amount: ₹{order.total?.toFixed(2) || '0.00'}
{/* Order Details Sidebar */}
{/* Order Actions */} Order Actions
{updating && (
Updating order status...
)}
{/* Customer Information */} Customer Information
{order.user?.name || 'Unknown User'}
{order.user?.email || 'No email'}
{order.user?.phone && (
{order.user.phone}
)}
{/* Shipping Information */} Shipping Address {order.shippingAddress ? (

{order.shippingAddress.firstName} {order.shippingAddress.lastName}

{order.shippingAddress.company && (

{order.shippingAddress.company}

)}

{order.shippingAddress.address1}

{order.shippingAddress.address2 && (

{order.shippingAddress.address2}

)}

{order.shippingAddress.city}, {order.shippingAddress.state} {order.shippingAddress.zipCode}

{order.shippingAddress.country}

{order.shippingAddress.phone && (

{order.shippingAddress.phone}

)}
) : (

No shipping address provided

)}
{/* Payment Information */} Payment Information
Payment Status: {order.status}
{order.razorpayOrderId && (
Razorpay Order ID:

{order.razorpayOrderId}

)} {order.razorpayPaymentId && (
Payment ID:

{order.razorpayPaymentId}

)}
Total Amount:

₹{order.total?.toFixed(2) || '0.00'}

) }