'use client'
import Layout from '@/hoc/Layout'
import { NextPage } from 'next'
import React, { useState, useMemo } from 'react'
import Menu from '../components/Menu'
import { useGetOrders, useGetReturnOrder } from './hooks/useOrdersData'
import { Order, ReturnOrder } from './types/Types'
import OrderTabs from './components/OrderTabs'
import OrderItem from './components/OrderItem'
import ReturnOrderItem from './components/ReturnOrderItem'


const Orders: NextPage = () => {

    const [activeTab, setActiveTab] = useState<'Processing' | 'Delivered' | 'Cancelled' | 'Returned'>('Processing')
    const { data: ordersData } = useGetOrders(activeTab);
    const { data: returnOrderData } = useGetReturnOrder();

    // محاسبه تعداد سفارشات در هر تب از داده‌های اصلی
    const tabCounts = useMemo(() => {
        if (!ordersData?.results?.orders) return { current: 0, delivered: 0, returned: 0, cancelled: 0 };

        return ordersData.results.orders.reduce((acc, order: Order) => {
            const status = (order.status || 'pending').toLowerCase();
            if (['pending', 'processing', 'shipped'].includes(status)) {
                acc.current++;
            } else if (status === 'delivered') {
                acc.delivered++;
            } else if (status === 'returned') {
                acc.returned++;
            } else if (status === 'cancelled') {
                acc.cancelled++;
            }
            return acc;
        }, { current: 0, delivered: 0, returned: 0, cancelled: 0 });
    }, [ordersData]);

    // تابع تبدیل وضعیت به فارسی
    const getStatusText = (status: string) => {
        const statusMap: { [key: string]: string } = {
            'pending': 'در انتظار پرداخت',
            'processing': 'در حال پردازش',
            'shipped': 'در حال ارسال',
            'delivered': 'تحویل شده',
            'returned': 'مرجوع شده',
            'cancelled': 'لغو شده'
        };
        return statusMap[status.toLowerCase()] || status;
    };


    return (
        <div className='p-3 sm:p-4 md:p-6'>
            <Menu pageActive='orders' />

            {/* Tabs */}
            <OrderTabs
                activeTab={activeTab}
                setActiveTab={setActiveTab}
                tabCounts={tabCounts}
            />

            {/* Orders List */}
            <div className='mt-4 sm:mt-6 space-y-3 sm:space-y-4'>
                {activeTab === 'Returned' ? (
                    // نمایش سفارشات مرجوعی
                    returnOrderData?.results?.returnOrders?.map((order: ReturnOrder) => (
                        <ReturnOrderItem
                            key={order._id}
                            order={order}
                        />
                    ))
                ) : (
                    // نمایش سفارشات عادی
                    ordersData?.results?.orders?.map((order: Order) => (
                        <OrderItem
                            key={order._id.toString()}
                            order={order}
                            getStatusText={getStatusText}
                        />
                    ))
                )}
            </div>
        </div>
    )
}

export default function OrdersWithLayout() {
    return (
        <Layout>
            <Orders />
        </Layout>
    )
}