'use client'
import { FC, useState } from 'react'
import { ArrowLeft, TaskSquare } from 'iconsax-react'
import { useRouter, useParams } from 'next/navigation'
import PageLoading from '@/components/PageLoading'
import Layout from '@/hoc/Layout'
import Menu from '../../components/Menu'
import OrderSidebar from './components/OrderSidebar'
import OrderMainContent from './components/OrderMainContent'
import CancelOrderModal from './components/CancelOrderModal'
import { useCancelOrder, useGetOrderDetail } from '../hooks/useOrdersData'
import { toast } from '@/components/Toast'
import { PRIMARY_COLOR } from '@/config/const'


const OrderDetail: FC = () => {
    const { id } = useParams()
    const { data: orderDetail } = useGetOrderDetail(id as string)
    const [showModalCancel, setShowModalCancel] = useState<boolean>(false)
    const cancelOrderMutation = useCancelOrder()
    const router = useRouter()

    const getStatusText = (status: string) => {
        const statusMap: Record<string, string> = {
            'processing': 'در حال پردازش',
            'shipped': 'ارسال شده',
            'delivered': 'تحویل داده شده',
            'cancelled': 'لغو شده'
        }
        return statusMap[status] || status
    }

    const onSubmit = async (cancelData: { reason: string; count: string; description: string }) => {
        try {
            // Prepare cancel items from all order items
            const cancelItems = orderDetail?.results.order.orderItems.flatMap(orderItem =>
                orderItem.shipmentItems.map(shipmentItem => {
                    const availableQuantity = shipmentItem.quantity - shipmentItem.cancelled_quantity - shipmentItem.returned_quantity

                    return {
                        orderItemId: orderItem._id,
                        shipmentItemId: shipmentItem._id,
                        quantity: availableQuantity,
                        comment: cancelData.description,
                        reason: cancelData.reason
                    }
                })
            ) || []

            await cancelOrderMutation.mutateAsync({
                orderId: Number(id),
                items: cancelItems
            })

            toast("درخواست لغو سفارش با موفقیت ثبت شد", "success")

            setShowModalCancel(false)
            router.push('/profile/orders')
        } catch {
            toast("مشکلی در ثبت درخواست لغو سفارش رخ داد", "error")
        }
    }

    return (
        <div className='w-full lg:px-10 px-4 mt-20'>

            <Menu pageActive='orders' />

            <div className='border p-6 rounded-2xl text-sm mt-7'>
                <div className='flex justify-between items-center border-b pb-6'>
                    <div className='flex gap-2 items-center'>
                        <button
                            onClick={() => router.push('/profile/orders')}
                            className='p-2 hover:bg-gray-100 rounded-lg transition-colors'
                        >
                            <ArrowLeft color='black' size={20} className="rotate-180" />
                        </button>
                        <div className="text-lg font-semibold">جزئیات سفارش</div>
                    </div>

                    <div className='flex gap-2 items-center cursor-pointer' onClick={() => router.push(`/profile/orders/${id}/return`)}>
                        <TaskSquare color={PRIMARY_COLOR} size={20} />
                        <div className='text-primary'>فرم درخواست مرجوعی</div>
                    </div>
                </div>

                {cancelOrderMutation.isPending ? (
                    <PageLoading />
                ) : orderDetail?.results.order ? (
                    <div className='mt-6 lg:flex-row flex-col flex gap-6 items-start'>
                        <OrderSidebar
                            orderData={{
                                payment: orderDetail.results.order.payment,
                                order: {
                                    _id: orderDetail.results.order._id.toString(),
                                    user: orderDetail.results.order.user,
                                    shipmentAddress: orderDetail.results.order.shipmentAddress,
                                    createdAt: orderDetail.results.order.createdAt
                                }
                            }}
                            orderId={orderDetail.results.order._id}
                        />

                        <OrderMainContent
                            orderItems={orderDetail.results.order.orderItems}
                            orderId={orderDetail.results.order._id.toString()}
                            getStatusText={getStatusText}
                            onCancelClick={() => setShowModalCancel(true)}
                        />
                    </div>
                ) : (
                    <div className='mt-6 text-center'>در حال بارگذاری...</div>
                )}
            </div>

            <CancelOrderModal
                showModalCancel={showModalCancel}
                setShowModalCancel={setShowModalCancel}
                onSubmit={onSubmit}
                isLoading={cancelOrderMutation.isPending}
                cancelReasons={orderDetail?.results.order.cancelReasons}
            />
        </div>
    )
}

export default function OrderDetailWithLayout() {
    return (
        <Layout>
            <OrderDetail />
        </Layout>
    )
}