Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

use "https://dev.naayiq.com/cart" to fetch the carts for the user if no orders show…

  1. User

    use "https://dev.naayiq.com/cart" to fetch the carts for the user if no orders show empty orders... the result may look like this: { "carts": [ { "id": 5031, "user_id": 20, "status": "Pending", "notes": "", "full_name": "Mustafa Kareem", "governorate": "baghdad", "city": "B", "address": "test", "closest_point": "test", "phone_number": "07752546762", "type": "home", "created_at": "2024-10-01T23:38:49.978Z", "coupon_id": null, "updated_at": "2024-10-01T23:38:49.978Z", "items": [ { "id": 5038, "cart_id": 5031, "product_id": 5016, "size_id": 5054, "color_id": null, "quantity": 1 } ] } ], "total": 1, "page": 1, "limit": 10 } focus on items... fetch the product by using... https://dev.naayiq.com/products/{product_id} the result will look something like this: {"product":{"id":204,"name":"‏Round Lab 1025 Dokdo Toner","description":"تونر يومي يساعد على تقشير البشرة وترطيبها.\nيحتوي على مياه البحر العميقة الغنية بالمعادن للحفاظ على المستوى الأمثل في توازن الماء والزيت للبشرة.\nويحتوي على EX-07 يزيل بشكل معتدل خلايا الجلد الميتة والدهون من أجل البشرة صحية.\nيحتوي على البانثينول والألانتوين والبيتين لحماية فعالة\nوتهدئة البشرة المتهيجة.","brand_id":121,"has_color":false,"has_size":true,"product_type":"size","price":"0.00","qty":0,"sold":0,"created_at":"2024-08-26T22:36:20.453Z","updated_at":"2024-09-15T18:13:25.335Z","categories":[{"id":169,"name":"Toners"}],"colors":[],"sizes":[{"id":1053,"name":"200 ml","price":"25000.00","qty":10,"sold":0,"color_id":null,"images":["1257.webp"]}],"images":[{"id":2452,"url":"1257.webp","color_id":null,"size_id":1053}]}} Merge it what I told you... also improve performance and stability and smoothness.. Also orders page doesn't work without applying filter! which is an issue! orders/page.jsx: 'use client' import React from 'react'; import Image from 'next/image'; import { useRouter } from 'next/navigation'; import Link from "next/link"; import {CircleArrowLeft} from "lucide-react";

    const EmptyOrders = () => { const router = useRouter();

    return (
        <div className="flex flex-col min-h-screen bg-white p-4 font-sans">
            <header className="flex items-center mb-6">
                <CircleArrowLeft size={52} strokeWidth={0.7} onClick={router.back} className="p-2 relative z-20" />
                <h1
                    className="text-3xl z-10 text-[#181717] left-0 right-0 absolute font-sans text-center font-medium">
                    Orders
                </h1>
            </header>
    
            <main className="flex-grow flex flex-col items-center">
                <div className="relative w-full h-[33vh]">
                    <Image
                        src="https://storage.naayiq.com/resources/empty_cart.gif"
                        alt="Empty orders"
                        fill
                        unoptimized={true}
                        priority={true}
                        quality={100}
                        className="object-contain"
                    />
                </div>
                <p className="text-3xl font-semibold font-serif text-black mb-12">No orders was found!</p>
                <div className="w-full font-serif text-sm ssm:text-base ssm2:text-lg font-medium flex justify-center items-center gap-4">
                    <Link
                        href={"/wishlist"}
                        className="px-3 ssm:px-6 flex items-center justify-center min-h-[56px] bg-[rgba(59,83,69,0.05)] text-[#3B5345] rounded-lg outline outline-1 outline-[#3B5345]">
                        Check Wishlist
                    </Link>
                    <Link href={"/"} className="min-h-[56px] flex items-center justify-center px-3 ssm:px-6 bg-[#3B5345] text-white rounded-lg">
                        Start Browsing
                    </Link>
                </div>
            </main>
        </div>
    );
    

    };

    export default EmptyOrders; MyOrders.jsx: 'use client' import React, {useEffect, useRef, useState} from 'react'; import Image from "next/image"; import {useRouter} from "next/navigation";

    import {MapPin, Search, Copy, X, Check, CircleArrowLeft} from 'lucide-react'; import Link from "next/link";

    const OrderCard = ({ id, status, productImages, price, quantity, orderDate, location }) => { const [copied, setCopied] = useState(false);

    const formatDate = (dateString) => {
        const date = new Date(dateString);
        const day = date.getDate().toString().padStart(2, '0');
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const year = date.getFullYear().toString().slice(-2);
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `${day}/${month}/${year}, ${hours}:${minutes}`;
    };
    
    const handleCopy = () => {
        navigator.clipboard.writeText(id);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
    };
    
    return (
        <Link prefetch={false} href={"/profile/orders/detail"} className="bg-white font-sans rounded-lg font-medium shadow-md p-4 max-w-sm">
            <div className="flex justify-between items-center mb-4">
                <div className="flex items-baseline gap-3">
                    <h2 className="text-lg">Order ID</h2>
                    <span className="text-[#695C5C] text-sm font-normal">#{id}</span>
                    <button onClick={handleCopy} className="focus:outline-none">
                        {copied ? <Check size={16} className="text-green-500" /> : <Copy size={16} className="text-gray-400" />}
                    </button>
                </div>
                <span className={`px-3 py-1 rounded-full text-sm ${status === 'Complete' ? 'bg-emerald-500 text-white' : 'bg-gray-200 text-gray-700'}`}>
          {status}
        </span>
            </div>
            <div className="flex mb-4 -space-x-4">
                {productImages.map((image, index) => (
                    <Image
                        key={index}
                        src={image}
                        width={80}
                        height={80}
                        alt={`Product ${index + 1}`}
                        className="rounded-full object-cover border-2 border-white"
                        style={{ zIndex: productImages.length - index }}
                    />
                ))}
            </div>
            <div className="flex gap-4 items-baseline mb-4 py-2 border-[#695C5C]/30 border-solid border-b">
                <span className="text-lg">{price.toLocaleString()} IQD</span>
                <span className="text-[#695C5C] text-sm font-normal">{quantity} Product{quantity > 1 ? 's' : ''}</span>
            </div>
            <div className="flex items-baseline justify-between font-normal text-black">
                <div className="flex items-center">
                    <MapPin size={16} className="mr-2" />
                    <span className="mr-4 text-lg">{location}</span>
                </div>
                <span className="text-[#695C5C] font-medium text-sm">{formatDate(orderDate)}</span>
            </div>
        </Link>
    );
    

    };

    const FilterModal = ({ isOpen, onClose, onApply }) => { const [status, setStatus] = useState('All'); const [duration, setDuration] = useState('Any Time'); const [isAnimating, setIsAnimating] = useState(true); const modalRef = useRef(null);

    useEffect(() => {
        let animationTimeout;
    
        if (isOpen) {
            // For slide-up, we need a slight delay to allow the element to be rendered before animating
            animationTimeout = setTimeout(() => {
                if (modalRef.current) {
                    modalRef.current.style.transform = 'translateY(0)';
                }
            }, 50); // Adjust the delay (in milliseconds) as needed
        } else {
            if (modalRef.current) {
                modalRef.current.style.transform = 'translateY(100%)';
            }
        }
    
        return () => clearTimeout(animationTimeout);
    }, [isOpen]);
    
    useEffect(() => {
        if (isOpen) {
            setIsAnimating(true);
            document.body.style.overflow = 'hidden';
        } else {
            document.body.style.overflow = 'auto';
        }
    
        return () => {
            document.body.style.overflow = 'unset';
        };
    }, [isOpen]);
    
    const handleApply = () => {
        onApply({ status, duration });
        handleClose();
    };
    
    const handleReset = () => {
        setStatus('All');
        setDuration('Any Time');
    };
    
    const handleClose = () => {
        setIsAnimating(true);
        setTimeout(function() {
            onClose()
        }, 300)
        setTimeout(function() {
            setIsAnimating(false)
        }, 400)
    }
    
    
    const handleOutsideClick = (e) => {
        if (modalRef.current && !modalRef.current.contains(e.target)) {
            handleClose();
        }
    };
    
    if (!isOpen && !isAnimating) return null;
    
    return (
        <div
            className={`fixed inset-0 items-end bg-black bg-opacity-50 flex bottom-0 top-0 z-50 transition-opacity duration-300 ease-in-out ${isOpen ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}
            onClick={handleOutsideClick}
        >
            <div
                ref={modalRef}
                style={{ transform: 'translateY(100%)' }} // Initial state: hidden
                className={`bg-white max-h-[80vh] justify-end rounded-lg w-full flex flex-col transition-transform duration-300 ease-in-out`}
            >
    
    
                <div className="flex justify-center pt-2">
                    <svg width="36" height="6" viewBox="0 0 36 6" fill="none" xmlns="http://www.w3.org/2000/svg"
                         onClick={handleClose}>
                        <rect opacity="0.7" width="36" height="6" rx="3" fill="#00003C"/>
                    </svg>
                </div>
                <div className="p-4 font-sans font-medium border-b flex justify-between items-center">
                    <h2 className="text-xl">Filter Orders</h2>
                    <button className="text-[#97C86C] text-sm font-medium" onClick={handleReset}>
                        Reset Filter
                    </button>
                </div>
                <div className="flex-grow font-medium font-serif overflow-auto p-4">
                    <div className="mb-6">
                        <h3 className="text-base font-sans mb-4">Status</h3>
                        {['All', 'On the way', 'Delivered', 'Cancelled'].map((option) => (
                            <label key={option} className="flex font-normal items-center mb-4 cursor-pointer">
                                <input
                                    type="radio"
                                    className="hidden"
                                    checked={status === option}
                                    onChange={() => setStatus(option)}
                                />
                                <div
                                    className={`w-6 h-6 rounded-full border flex items-center justify-center mr-3 ${status === option ? 'border-[#3B5345] bg-white' : 'border-gray-300'}`}>
                                    {status === option && <div className="w-4 h-4 bg-[#97C86C] rounded-full"></div>}
                                </div>
                                <span className="text-lg">{option}</span>
                            </label>
                        ))}
                    </div>
                    <div>
                        <h3 className="text-base font-sans mb-4">Duration</h3>
                        {['Any Time', 'This Month', 'Last 3 Months', 'Last Year'].map((option) => (
                            <label key={option} className="flex font-normal items-center mb-4 cursor-pointer">
                                <input
                                    type="radio"
                                    className="hidden"
                                    checked={duration === option}
                                    onChange={() => setDuration(option)}
                                />
                                <div
                                    className={`w-6 h-6 rounded-full border flex items-center justify-center mr-3 ${duration === option ? 'bg-white border-[#3B5345]' : 'border-gray-300'}`}>
                                    {duration === option && <div className="w-4 h-4 bg-[#97C86C] rounded-full"></div>}
                                </div>
                                <span className="text-lg">{option}</span>
                            </label>
                        ))}
                    </div>
                </div>
                <div className="p-4">
                    <button
                        className="w-full font-sans bg-[#3B5345] text-white py-3 rounded-lg text-lg font-medium"
                        onClick={handleApply}
                    >
                        Apply Filter
                    </button>
                </div>
            </div>
        </div>
    );
    

    };

    const MyOrders = () => { const router = useRouter(); const [searchTerm, setSearchTerm] = useState(''); const [isFilterOpen, setIsFilterOpen] = useState(false); const [filters, setFilters] = useState({status: '', date: ''});

    const orders = [
        {
            id: '1000000',
            date: Date.now(),
            status: 'Complete',
            location: 'Baghdad arasat',
            price: 150000,
            quantity: 6,
            productImages: ["/water.webp", '/cream.webp'],
        },
        {
            id: '1020000',
            date: Date.now(),
            status: 'Canceled',
            location: 'Baghdad arasat',
            price: 150000,
            quantity: 6,
            productImages: ["/water.png", '/cream.png']
        },
        {
            id: '1030000',
            date: Date.now(),
            status: 'On The Way',
            location: 'Baghdad arasat',
            price: 150000,
            quantity: 6,
            productImages: ["/water.png", '/cream.png'],
        },
    ];
    
    const filteredOrders = orders.filter((order) => {
        const matchesSearch = order.id.includes(searchTerm) || order.location.toLowerCase().includes(searchTerm.toLowerCase());
        const matchesStatus = filters.status === 'All' || order.status === filters.status;
        const matchesDuration = filters.duration === 'Any Time' || (
            filters.duration === 'Past Month' && /* add logic for this month */ true ||
            filters.duration === 'Past 3 Months' && /* add logic for last 3 months */ true ||
            filters.duration === 'Past Year' && /* add logic for last year */ true
        );
        return matchesSearch && matchesStatus && matchesDuration;
    });
    
    return (
        <div className="mt-2 px-4">
            <header className="flex items-center mb-6">
                <CircleArrowLeft size={52} strokeWidth={0.7} onClick={router.back} className="p-2 relative z-20" />
                <h1 className="text-3xl z-10 text-[#181717] left-0 right-0 absolute font-sans text-center font-medium">My Orders</h1>
            </header>
            <div className="flex items-center mb-4">
                <div className="relative flex-grow">
                    <input
                        type="text"
                        placeholder="Search for orders"
                        className="w-full py-2 pl-10 pr-4 border rounded-l-lg"
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                    />
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                </div>
                <button
                    className="bg-gray-100 py-2 px-4 rounded-r-lg"
                    onClick={() => setIsFilterOpen(true)}
                >
                    Filter
                </button>
            </div>
            <div className="space-y-4">
                {filteredOrders.map((order) => (
                    <OrderCard
                        key={order.id}
                        id={order.id}
                        status={order.status}
                        price={order.price}
                        quantity={order.quantity}
                        orderDate={order.date}
                        location={order.location}
                        productImages={order.productImages}
                    />
                ))}
            </div>
            <FilterModal
                isOpen={isFilterOpen}
                onClose={() => setIsFilterOpen(false)}
                onApply={setFilters}
            />
        </div>
    );
    

    };

    export default MyOrders; OrderDetail.jsx: 'use client' import Image from "next/image"; import React from "react"; import {useRouter} from "next/navigation"; import {CircleArrowLeft} from "lucide-react";

    export default function OrderDetails({orderID}) { const orderSteps = [ { label: 'Order Confirm', date: '6/6/23, 8:44PM', isCompleted: true }, { label: 'Shipped', date: '6/6/23, 10:54PM', isCompleted: true }, { label: 'Delivered', date: '7/6/23, 11:33AM', isCompleted: true }, ]; const orderDetails = { id: '#1000000', total: '125,000 IQD', date: '6/6/23, 8:44PM', status: 'Order Confirm', products: [ { image: '/water.webp', title: 'Rare Beauty Blush Liquid', color: 'Happy', size: '25 ml', qty: 1, price: '50,000 IQD' }, { image: '/cream.webp', title: 'GISOU - Mini Honey Infused Hair Oil', size: '25 ml', qty: 1, price: '43,000 IQD' }, { image: '/korean.webp', title: 'Hairburst Shampoo & conditioner', color: 'Happy', qty: 1, price: '50,000 IQD' } ], shippingAddress: { city: 'Baghdad', area: 'Arassat', details: 'Near the International Bank', phone: '077000000' }, priceDetails: { price: '143,000 IQD', deliveryCost: '5,000 IQD', discount: '8,000 IQD', totalPrice: '140,000 IQD' } } const router = useRouter() return ( <> Order Details Order ID {orderDetails.id} Total {orderDetails.total} Date {orderDetails.date} Track Orders <OrderedProducts products={[{ image: '/water.webp', name: 'Rare Beauty Blush Liquid', details: ['Color: Happy', 'Size: 25 ml'], price: '50,000', }, { image: '/cream.webp', name: 'Cream', details: ['Color: Happy', 'Size: 25 ml'], price: '50,000' }]}/>

            <div>
                <p className="font-sans font-medium mb-6 text-xl">Shipping Address</p>
                <div
                    className="bg-skintone font-medium border border-[#695C5C]/30 space-y-5 border-solid font-serif p-4">
                    <p>{orderDetails.shippingAddress.city}</p>
                    <p>{orderDetails.shippingAddress.area}</p>
                    <p>{orderDetails.shippingAddress.details}</p>
                    <p>{orderDetails.shippingAddress.phone}</p>
                </div>
                <p className="font-sans font-medium text-xl">Price Details</p>
                <div
                    className="bg-skintone font-medium border border-[#695C5C]/30 space-y-5 border-solid font-serif p-4">
                    <p>{orderDetails.priceDetails.price}</p>
                    <p>{orderDetails.priceDetails.deliveryCost}</p>
                    <p>{orderDetails.priceDetails.discount}</p>
                    <p className="font-semibold text-xl">{orderDetails.priceDetails.totalPrice}</p>
                </div>
                <button className="bg-[#C91C1C] py-3 text-white font-sans text-xl font-bold w-full rounded-xl">Cancel
                    Order
                </button>
            </div>
        </>
    )
    

    }

    const OrderTrackingStep = ({label, date, isCompleted, isLast}) => ( <div className={w-8 h-8 rounded-full border-2 ${isCompleted ? 'bg-green-500 border-green-500' : 'bg-white border-gray-300'} flex items-center justify-center}> {isCompleted && ( )} {!isLast && <div className={absolute top-8 left-1/2 w-0.5 h-full -translate-x-1/2 ${isCompleted ? 'bg-green-500' : 'bg-gray-300'}}>} {label} {date || 'Not Yet'} );

    const OrderTracking = ({ steps }) => ( {steps.map((step, index) => ( <OrderTrackingStep key={step.label} label={step.label} date={step.date} isCompleted={step.isCompleted} isLast={index === steps.length - 1} /> ))} );

    const ProductItem = ({ image, name, details, price }) => ( {name} {details.map((detail, index) => ( {detail} ))} Qty:1 ▼ {price} IQD );

    const OrderedProducts = ({products}) => ( <> Ordered Product {products.map((product, index) => ( <ProductItem key={index} {...product} /> ))} </> );

    Notice that the order detail may also have rejected state...

  2. Assistant

    To enhance your orders management system, we'll integrate fetching cart data from the provided API, merge it with detailed product information, and ensure the orders page functions smoothly without requiring users to apply filters. Additionally, we'll improve performance and handle edge cases effectively.

    Here's a comprehensive guide to achieving this:

    1. Overview of the Improvements

    • Data Fetching and Merging:

      • Fetch Carts: Retrieve the user's carts from https://dev.naayiq.com/cart.
      • Fetch Product Details: For each item in the carts, fetch detailed product information from https://dev.naayiq.com/products/{product_id}.
      • Merge Data: Combine cart items with their respective product details to create a comprehensive dataset for rendering.
    • Performance Enhancements:

      • Parallel Fetching: Utilize Promise.all to fetch all product details concurrently, reducing load times.
      • Caching Product Data: Implement caching to avoid redundant fetches for the same product_id, enhancing efficiency.
      • Error Handling: Incorporate robust error handling to manage API failures gracefully.
    • UI/UX Improvements:

      • Conditional Rendering: Display the EmptyOrders component when there are no orders.
      • Filter Functionality: Ensure the orders page works seamlessly both with and without applied filters.
      • Loading States: Provide visual feedback during data fetching to improve user experience.

    2. Implementation Details

    We'll refactor the MyOrders.jsx component to include the data fetching and merging logic, handle loading and error states, and fix the filter functionality issue.

    a. Create a Custom Hook for Fetching and Merging Data

    Creating a custom hook will encapsulate the data fetching logic, making the component cleaner and more maintainable.

    // hooks/useFetchOrders.js
    import { useEffect, useState } from 'react';
    
    const useFetchOrders = (userId) => {
        const [orders, setOrders] = useState([]);
        const [loading, setLoading] = useState(true);
        const [error, setError] = useState(null);
    
        useEffect(() => {
            const fetchCarts = async () => {
                try {
                    const res = await fetch('https://dev.naayiq.com/cart', {
                        headers: {
                            'Content-Type': 'application/json',
                            // Include authentication headers if required
                        }
                    });
    
                    if (!res.ok) {
                        throw new Error('Failed to fetch carts.');
                    }
    
                    const data = await res.json();
    
                    if (data.carts && data.carts.length > 0) {
                        // Extract unique product_ids to avoid redundant fetches
                        const uniqueProductIds = [
                            ...new Set(
                                data.carts.flatMap(cart => cart.items.map(item => item.product_id))
                            )
                        ];
    
                        // Fetch all products in parallel
                        const productPromises = uniqueProductIds.map(id =>
                            fetch(`https://dev.naayiq.com/products/${id}`).then(response => {
                                if (!response.ok) {
                                    throw new Error(`Failed to fetch product with ID ${id}`);
                                }
                                return response.json();
                            })
                        );
    
                        const productsData = await Promise.all(productPromises);
                        // Create a map for easy lookup
                        const productsMap = {};
                        productsData.forEach(prod => {
                            productsMap[prod.product.id] = prod.product;
                        });
    
                        // Merge product details into cart items
                        const mergedCarts = data.carts.map(cart => ({
                            ...cart,
                            items: cart.items.map(item => ({
                                ...item,
                                product: productsMap[item.product_id]
                            }))
                        }));
    
                        setOrders(mergedCarts);
                    } else {
                        setOrders([]);
                    }
                } catch (err) {
                    setError(err.message);
                } finally {
                    setLoading(false);
                }
            };
    
            fetchCarts();
        }, [userId]);
    
        return { orders, loading, error };
    };
    
    export default useFetchOrders;
    

    b. Update MyOrders.jsx to Utilize the Custom Hook

    We'll integrate the custom hook into the MyOrders.jsx component, handle different states (loading, error, empty), and fix the filter functionality.

    // components/MyOrders.jsx
    'use client';
    
    import React, { useState, useEffect } from 'react';
    import Image from "next/image";
    import { useRouter } from "next/navigation";
    import Link from "next/link";
    import { CircleArrowLeft, Search, Filter } from 'lucide-react';
    import useFetchOrders from '../hooks/useFetchOrders';
    import EmptyOrders from './EmptyOrders';
    import FilterModal from './FilterModal'; // Ensure this is correctly imported
    
    const OrderCard = ({ order }) => {
        const [copied, setCopied] = useState(false);
    
        const formatDate = (dateString) => {
            const date = new Date(dateString);
            const day = date.getDate().toString().padStart(2, '0');
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const year = date.getFullYear().toString().slice(-2);
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            return `${day}/${month}/${year}, ${hours}:${minutes}`;
        };
    
        const handleCopy = (e) => {
            e.preventDefault(); // Prevent navigating when clicking the copy button
            navigator.clipboard.writeText(order.id);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        };
    
        return (
            <Link prefetch={false} href={`/profile/orders/detail/${order.id}`} className="bg-white font-sans rounded-lg font-medium shadow-md p-4 max-w-sm block">
                <div className="flex justify-between items-center mb-4">
                    <div className="flex items-baseline gap-3">
                        <h2 className="text-lg">Order ID</h2>
                        <span className="text-[#695C5C] text-sm font-normal">#{order.id}</span>
                        <button onClick={handleCopy} className="focus:outline-none">
                            {copied ? <Check size={16} className="text-green-500" /> : <Copy size={16} className="text-gray-400" />}
                        </button>
                    </div>
                    <span className={`px-3 py-1 rounded-full text-sm ${order.status === 'Complete' ? 'bg-emerald-500 text-white' : order.status === 'Cancelled' ? 'bg-red-500 text-white' : 'bg-gray-200 text-gray-700'}`}>
                        {order.status}
                    </span>
                </div>
                <div className="flex mb-4 -space-x-4">
                    {order.items.map((item, index) => (
                        <Image
                            key={index}
                            src={item.product.images[0].url} // Assuming the first image
                            width={80}
                            height={80}
                            alt={`Product ${index + 1}`}
                            className="rounded-full object-cover border-2 border-white"
                            style={{ zIndex: order.items.length - index }}
                        />
                    ))}
                </div>
                <div className="flex gap-4 items-baseline mb-4 py-2 border-[#695C5C]/30 border-solid border-b">
                    <span className="text-lg">{order.items.reduce((acc, item) => acc + parseFloat(item.product.price) * item.quantity, 0).toLocaleString()} IQD</span>
                    <span className="text-[#695C5C] text-sm font-normal">{order.items.reduce((acc, item) => acc + item.quantity, 0)} Product{order.items.reduce((acc, item) => acc + item.quantity, 0) > 1 ? 's' : ''}</span>
                </div>
                <div className="flex items-baseline justify-between font-normal text-black">
                    <div className="flex items-center">
                        {/* Assuming location is part of the cart data */}
                        <MapPin size={16} className="mr-2" />
                        <span className="mr-4 text-lg">{order.address}</span>
                    </div>
                    <span className="text-[#695C5C] font-medium text-sm">{formatDate(order.created_at)}</span>
                </div>
            </Link>
        );
    };
    
    const MyOrders = () => {
        const router = useRouter();
        const [searchTerm, setSearchTerm] = useState('');
        const [isFilterOpen, setIsFilterOpen] = useState(false);
        const [filters, setFilters] = useState({ status: 'All', duration: 'Any Time' });
        const { orders, loading, error } = useFetchOrders(/* Pass user ID if needed */);
    
        // Handle Filter Application
        const handleApplyFilters = (appliedFilters) => {
            setFilters(appliedFilters);
            setIsFilterOpen(false);
        };
    
        // Filter Logic
        const filteredOrders = orders.filter((order) => {
            const matchesSearch = order.id.toString().includes(searchTerm) || order.full_name.toLowerCase().includes(searchTerm.toLowerCase()) || order.address.toLowerCase().includes(searchTerm.toLowerCase());
            const matchesStatus = filters.status === 'All' || order.status.toLowerCase() === filters.status.toLowerCase();
            
            // Duration Filter Logic
            let matchesDuration = true;
            const orderDate = new Date(order.created_at);
            const now = new Date();
            if (filters.duration !== 'Any Time') {
                let compareDate;
                switch (filters.duration) {
                    case 'This Month':
                        compareDate = new Date(now.getFullYear(), now.getMonth(), 1);
                        break;
                    case 'Last 3 Months':
                        compareDate = new Date(now.getFullYear(), now.getMonth() - 3, 1);
                        break;
                    case 'Last Year':
                        compareDate = new Date(now.getFullYear() - 1, now.getMonth(), 1);
                        break;
                    default:
                        compareDate = new Date(0);
                }
                matchesDuration = orderDate >= compareDate;
            }
    
            return matchesSearch && matchesStatus && matchesDuration;
        });
    
        if (loading) {
            return (
                <div className="flex justify-center items-center h-screen">
                    <p className="text-xl">Loading orders...</p>
                </div>
            );
        }
    
        if (error) {
            return (
                <div className="flex justify-center items-center h-screen">
                    <p className="text-xl text-red-500">Error: {error}</p>
                </div>
            );
        }
    
        if (orders.length === 0) {
            return <EmptyOrders />;
        }
    
        return (
            <div className="mt-2 px-4">
                <header className="flex items-center mb-6">
                    <CircleArrowLeft size={52} strokeWidth={0.7} onClick={() => router.back()} className="p-2 relative z-20 cursor-pointer" />
                    <h1 className="text-3xl z-10 text-[#181717] left-0 right-0 absolute font-sans text-center font-medium">My Orders</h1>
                </header>
                <div className="flex items-center mb-4">
                    <div className="relative flex-grow">
                        <input
                            type="text"
                            placeholder="Search for orders"
                            className="w-full py-2 pl-10 pr-4 border rounded-l-lg"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                        />
                        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                    </div>
                    <button
                        className="flex items-center bg-gray-100 py-2 px-4 rounded-r-lg ml-2"
                        onClick={() => setIsFilterOpen(true)}
                    >
                        <Filter size={20} className="mr-2" />
                        Filter
                    </button>
                </div>
                {filteredOrders.length > 0 ? (
                    <div className="space-y-4">
                        {filteredOrders.map((order) => (
                            <OrderCard key={order.id} order={order} />
                        ))}
                    </div>
                ) : (
                    <EmptyOrders />
                )}
                <FilterModal
                    isOpen={isFilterOpen}
                    onClose={() => setIsFilterOpen(false)}
                    onApply={handleApplyFilters}
                />
            </div>
        );
    };
    
    export default MyOrders;
    

    c. Update the EmptyOrders Component

    Ensure the EmptyOrders component is properly imported and displays when there are no orders after filtering.

    // components/EmptyOrders.jsx
    'use client';
    
    import React from 'react';
    import Image from 'next/image';
    import { useRouter } from 'next/navigation';
    import Link from "next/link";
    import { CircleArrowLeft } from "lucide-react";
    
    const EmptyOrders = () => {
        const router = useRouter();
    
        return (
            <div className="flex flex-col min-h-screen bg-white p-4 font-sans items-center justify-center">
                <header className="flex items-center mb-6 w-full relative">
                    <CircleArrowLeft size={52} strokeWidth={0.7} onClick={() => router.back()} className="p-2 z-20 cursor-pointer" />
                    <h1 className="text-3xl z-10 text-[#181717] left-0 right-0 absolute font-sans text-center font-medium">
                        Orders
                    </h1>
                </header>
    
                <main className="flex-grow flex flex-col items-center">
                    <div className="relative w-full h-[33vh]">
                        <Image
                            src="https://storage.naayiq.com/resources/empty_cart.gif"
                            alt="Empty orders"
                            fill
                            unoptimized={true}
                            priority={true}
                            quality={100}
                            className="object-contain"
                        />
                    </div>
                    <p className="text-3xl font-semibold font-serif text-black mb-12">No orders were found!</p>
                    <div className="w-full font-serif text-sm ssm:text-base ssm2:text-lg font-medium flex justify-center items-center gap-4">
                        <Link
                            href="/wishlist"
                            className="px-3 ssm:px-6 flex items-center justify-center min-h-[56px] bg-[rgba(59,83,69,0.05)] text-[#3B5345] rounded-lg outline outline-1 outline-[#3B5345]">
                            Check Wishlist
                        </Link>
                        <Link href="/" className="min-h-[56px] flex items-center justify-center px-3 ssm:px-6 bg-[#3B5345] text-white rounded-lg">
                            Start Browsing
                        </Link>
                    </div>
                </main>
            </div>
        );
    };
    
    export default EmptyOrders;
    

    d. Enhance the FilterModal Component

    Ensure the FilterModal component correctly manages filter states and animations.

    // components/FilterModal.jsx
    'use client';
    
    import React, { useEffect, useRef, useState } from 'react';
    
    const FilterModal = ({ isOpen, onClose, onApply }) => {
        const [status, setStatus] = useState('All');
        const [duration, setDuration] = useState('Any Time');
        const [isAnimating, setIsAnimating] = useState(false);
        const modalRef = useRef(null);
    
        useEffect(() => {
            if (isOpen) {
                setIsAnimating(true);
                document.body.style.overflow = 'hidden';
            } else {
                setIsAnimating(false);
                document.body.style.overflow = 'auto';
            }
    
            return () => {
                document.body.style.overflow = 'unset';
            };
        }, [isOpen]);
    
        const handleApply = () => {
            onApply({ status, duration });
            onClose();
        };
    
        const handleReset = () => {
            setStatus('All');
            setDuration('Any Time');
        };
    
        const handleOutsideClick = (e) => {
            if (modalRef.current && !modalRef.current.contains(e.target)) {
                onClose();
            }
        };
    
        if (!isOpen && !isAnimating) return null;
    
        return (
            <div
                className={`fixed inset-0 flex items-end justify-center bg-black bg-opacity-50 z-50 transition-opacity duration-300 ease-in-out ${isOpen ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}
                onClick={handleOutsideClick}
            >
                <div
                    ref={modalRef}
                    className={`bg-white max-h-[80vh] rounded-t-lg w-full p-4 transform transition-transform duration-300 ease-in-out ${isOpen ? 'translate-y-0' : 'translate-y-full'}`}
                    onClick={(e) => e.stopPropagation()} // Prevent closing when clicking inside the modal
                >
                    <div className="flex justify-center pb-4">
                        <div className="w-12 h-1 bg-gray-300 rounded-full" onClick={onClose}></div>
                    </div>
                    <div className="p-4">
                        <h2 className="text-xl font-semibold mb-4">Filter Orders</h2>
                        <div className="mb-6">
                            <h3 className="text-base font-medium mb-2">Status</h3>
                            {['All', 'On the way', 'Delivered', 'Cancelled'].map((option) => (
                                <label key={option} className="flex items-center mb-2 cursor-pointer">
                                    <input
                                        type="radio"
                                        name="status"
                                        value={option}
                                        checked={status === option}
                                        onChange={() => setStatus(option)}
                                        className="hidden"
                                    />
                                    <span className={`w-4 h-4 mr-2 flex items-center justify-center border ${status === option ? 'border-green-500' : 'border-gray-300'} rounded-full`}>
                                        {status === option && <span className="w-2 h-2 bg-green-500 rounded-full"></span>}
                                    </span>
                                    {option}
                                </label>
                            ))}
                        </div>
                        <div className="mb-6">
                            <h3 className="text-base font-medium mb-2">Duration</h3>
                            {['Any Time', 'This Month', 'Last 3 Months', 'Last Year'].map((option) => (
                                <label key={option} className="flex items-center mb-2 cursor-pointer">
                                    <input
                                        type="radio"
                                        name="duration"
                                        value={option}
                                        checked={duration === option}
                                        onChange={() => setDuration(option)}
                                        className="hidden"
                                    />
                                    <span className={`w-4 h-4 mr-2 flex items-center justify-center border ${duration === option ? 'border-blue-500' : 'border-gray-300'} rounded-full`}>
                                        {duration === option && <span className="w-2 h-2 bg-blue-500 rounded-full"></span>}
                                    </span>
                                    {option}
                                </label>
                            ))}
                        </div>
                        <div className="flex justify-end gap-4">
                            <button
                                className="px-4 py-2 bg-red-500 text-white rounded-lg"
                                onClick={handleReset}
                            >
                                Reset
                            </button>
                            <button
                                className="px-4 py-2 bg-green-500 text-white rounded-lg"
                                onClick={handleApply}
                            >
                                Apply
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        );
    };
    
    export default FilterModal;
    

    3. Additional Recommendations

    • Authentication: Ensure that API calls to https://dev.naayiq.com/cart and https://dev.naayiq.com/products/{product_id} include necessary authentication tokens or headers if required.

    • Pagination: If the number of orders is large, implement pagination or infinite scrolling to enhance performance.

    • Optimistic UI Updates: For actions like canceling an order, consider implementing optimistic UI updates to provide immediate feedback to users.

    • Accessibility: Ensure that all interactive elements are accessible via keyboard navigation and screen readers.

    • Responsive Design: Verify that all components are responsive and render correctly on various devices.

    4. Final Directory Structure

    For clarity, here's how your directory structure might look:

    components/
    │
    ├── EmptyOrders.jsx
    ├── FilterModal.jsx
    ├── MyOrders.jsx
    ├── OrderCard.jsx
    ├── ... (other components)
    │
    hooks/
    │
    └── useFetchOrders.js
    

    5. Complete Example

    Here's a consolidated view of how all components fit together.

    a. useFetchOrders.js

    (As provided above)

    b. EmptyOrders.jsx

    (As provided above)

    c. FilterModal.jsx

    (As provided above)

    d. MyOrders.jsx

    (As provided above)

    e. OrderCard.jsx

    If you prefer to separate the OrderCard into its own component:

    // components/OrderCard.jsx
    'use client';
    
    import React, { useState } from 'react';
    import Image from "next/image";
    import Link from "next/link";
    import { Check, Copy } from 'lucide-react';
    import { MapPin } from 'lucide-react';
    
    const OrderCard = ({ order }) => {
        const [copied, setCopied] = useState(false);
    
        const formatDate = (dateString) => {
            const date = new Date(dateString);
            const day = date.getDate().toString().padStart(2, '0');
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const year = date.getFullYear().toString().slice(-2);
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            return `${day}/${month}/${year}, ${hours}:${minutes}`;
        };
    
        const handleCopy = (e) => {
            e.preventDefault(); // Prevent navigating when clicking the copy button
            navigator.clipboard.writeText(order.id);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        };
    
        return (
            <Link prefetch={false} href={`/profile/orders/detail/${order.id}`} className="bg-white font-sans rounded-lg font-medium shadow-md p-4 max-w-sm block">
                <div className="flex justify-between items-center mb-4">
                    <div className="flex items-baseline gap-3">
                        <h2 className="text-lg">Order ID</h2>
                        <span className="text-[#695C5C] text-sm font-normal">#{order.id}</span>
                        <button onClick={handleCopy} className="focus:outline-none">
                            {copied ? <Check size={16} className="text-green-500" /> : <Copy size={16} className="text-gray-400" />}
                        </button>
                    </div>
                    <span className={`px-3 py-1 rounded-full text-sm ${order.status === 'Complete' ? 'bg-emerald-500 text-white' : order.status === 'Cancelled' ? 'bg-red-500 text-white' : 'bg-gray-200 text-gray-700'}`}>
                        {order.status}
                    </span>
                </div>
                <div className="flex mb-4 -space-x-4">
                    {order.items.map((item, index) => (
                        <Image
                            key={index}
                            src={item.product.images[0].url} // Assuming the first image
                            width={80}
                            height={80}
                            alt={`Product ${index + 1}`}
                            className="rounded-full object-cover border-2 border-white"
                            style={{ zIndex: order.items.length - index }}
                        />
                    ))}
                </div>
                <div className="flex gap-4 items-baseline mb-4 py-2 border-[#695C5C]/30 border-solid border-b">
                    <span className="text-lg">{order.items.reduce((acc, item) => acc + parseFloat(item.product.price) * item.quantity, 0).toLocaleString()} IQD</span>
                    <span className="text-[#695C5C] text-sm font-normal">{order.items.reduce((acc, item) => acc + item.quantity, 0)} Product{order.items.reduce((acc, item) => acc + item.quantity, 0) > 1 ? 's' : ''}</span>
                </div>
                <div className="flex items-baseline justify-between font-normal text-black">
                    <div className="flex items-center">
                        {/* Assuming location is part of the cart data */}
                        <MapPin size={16} className="mr-2" />
                        <span className="mr-4 text-lg">{order.address}</span>
                    </div>
                    <span className="text-[#695C5C] font-medium text-sm">{formatDate(order.created_at)}</span>
                </div>
            </Link>
        );
    };
    
    export default OrderCard;
    

    6. Conclusion

    By integrating the above changes, your orders page will:

    • Efficiently fetch and display user orders with detailed product information.
    • Handle cases with no orders gracefully by showing an EmptyOrders component.
    • Offer robust filtering options that work seamlessly without requiring users to apply them explicitly.
    • Enhance performance through parallel data fetching and data caching.
    • Improve the overall user experience with better loading states and error handling.

    Ensure you test all functionalities thoroughly across different scenarios to maintain stability and a smooth user experience.

    If you encounter any further issues or need additional features, feel free to ask!