'use client'
import Layout from '@/hoc/Layout'
import { type NextPage } from 'next'
import { useParams, useRouter } from 'next/navigation'
import { useState } from 'react'
import { useGetOrderDetail, useCancelOrder, useGetCancelReasons } from '../../hooks/useOrdersData'
import ProductSelection from './components/ProductSelection'
import CancelForm from './components/CancelForm'
import { toast } from '@/components/Toast'
import { extractErrorMessage } from '@/helpers/errorUtils'

const CancelOrderPage: NextPage = () => {
    const { id } = useParams()
    const router = useRouter()
    const { data: order, isLoading: isOrderLoading } = useGetOrderDetail(id as string)
    const cancelOrderMutation = useCancelOrder()
    const { data: cancelReasons } = useGetCancelReasons()
    const [selectedItems, setSelectedItems] = useState<string[]>([])

    const handleItemSelect = (itemId: string, checked: boolean) => {
        if (checked) {
            setSelectedItems(prev => [...prev, itemId])
        } else {
            setSelectedItems(prev => prev.filter(id => id !== itemId))
        }
    }

    const handleCancelSubmit = async (formData: { reason: string; description: string }) => {
        if (selectedItems.length === 0) {
            toast('هیچ آیتمی انتخاب نشده است', 'error')
            return
        }


        const cancelItems = selectedItems.map(itemId => {
            // Find the order item that contains this shipment item
            const orderItem = order?.results.order.orderItems.find(orderItem =>
                orderItem.shipmentItems.some(shipmentItem => shipmentItem._id === itemId)
            )

            const shipmentItem = orderItem?.shipmentItems.find(item => item._id === itemId)

            if (!orderItem || !shipmentItem) return null

            const availableQuantity = shipmentItem.quantity - shipmentItem.cancelled_quantity - shipmentItem.returned_quantity

            return {
                orderItemId: orderItem._id,
                shipmentItemId: shipmentItem._id,
                quantity: availableQuantity,
                comment: formData.description,
                reason: formData.reason
            }
        }).filter(Boolean) as { orderItemId: string; shipmentItemId: string; quantity: number; comment: string; reason: string }[]

        await cancelOrderMutation.mutateAsync({
            orderId: Number(id),
            items: cancelItems
        }, {
            onSuccess: () => {
                toast('درخواست لغو سفارش با موفقیت ثبت شد', 'success')
                router.push(`/profile/orders/${id}`)
            },
            onError: (error) => {
                toast(extractErrorMessage(error), 'error')
            }
        })

    }

    // Flatten all shipment items from all order items
    const allShipmentItems = order?.results.order.orderItems
        .flatMap(orderItem => orderItem.shipmentItems) || []

    if (isOrderLoading) {
        return (
            <Layout>
                <div className='mt-14 px-4 sm:px-8 lg:px-20'>
                    <div className='flex justify-center items-center min-h-[400px]'>
                        <div className='text-center'>
                            <div className='animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4'></div>
                            <p>در حال بارگذاری...</p>
                        </div>
                    </div>
                </div>
            </Layout>
        )
    }

    if (!order) {
        return (
            <Layout>
                <div className='mt-14 px-4 sm:px-8 lg:px-20'>
                    <div className='text-center min-h-[400px] flex items-center justify-center'>
                        <p>سفارش یافت نشد</p>
                    </div>
                </div>
            </Layout>
        )
    }

    return (
        <Layout>
            <div className='mt-14 px-4 sm:px-8 lg:px-20  mx-auto'>
                <div className='mb-8'>
                    <h1 className='text-2xl font-bold mb-2'>لغو سفارش</h1>
                    <p className='text-gray-600'>شماره سفارش: {order.results.order._id}</p>
                </div>

                <div className='space-y-8'>
                    <ProductSelection
                        items={allShipmentItems}
                        selectedItems={selectedItems}
                        onItemSelect={handleItemSelect}
                    />

                    {selectedItems.length > 0 && (
                        <CancelForm
                            onSubmit={handleCancelSubmit}
                            isLoading={cancelOrderMutation.isPending}
                            cancelReasons={cancelReasons?.results.reasons || []}
                            selectedItemsCount={selectedItems.length}
                        />
                    )}
                </div>
            </div>
        </Layout>
    )
}

export default CancelOrderPage