'use client'
import Layout from '@/hoc/Layout'
import { type NextPage } from 'next'
import { useParams, useRouter } from 'next/navigation'
import { useState } from 'react'
import { useGetOrderDetail, useReturnOrder, useGetReturnReasons } from '../../hooks/useOrdersData'
import ProductSelection from './components/ProductSelection'
import ReturnForm from './components/ReturnForm'
import ReturnConfirmation from './components/ReturnConfirmation'
import { toast } from '@/components/Toast'
import { extractErrorMessage } from '@/helpers/errorUtils'
import { Button } from '@/components/ui/button'

type Step = 1 | 2 | 3

interface FormData {
    quantities: { [key: string]: number }
    reason: string
    description: string
    images: File[]
}

const ReturnPage: NextPage = () => {
    const { id } = useParams()
    const router = useRouter()
    const { data: order, isLoading: isOrderLoading } = useGetOrderDetail(id as string)
    const returnOrderMutation = useReturnOrder()
    const { data: returnReasons } = useGetReturnReasons()

    const [currentStep, setCurrentStep] = useState<Step>(1)
    const [selectedItems, setSelectedItems] = useState<string[]>([])
    const [formData, setFormData] = useState<FormData | null>(null)
    const [imagePreviewUrls, setImagePreviewUrls] = useState<string[]>([])

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

    const handleFormSubmit = (data: FormData) => {
        setFormData(data)
        // ایجاد preview URLs برای تصاویر
        const previewUrls = data.images.map(file => URL.createObjectURL(file))
        setImagePreviewUrls(previewUrls)
        setCurrentStep(3)
    }

    const handleFinalSubmit = async () => {
        if (!formData || selectedItems.length === 0) {
            toast('اطلاعات ناقص است', 'error')
            return
        }

        // تبدیل تصاویر به base64 یا URL
        const imagePromises = formData.images.map(async (file) => {
            return new Promise<string>((resolve) => {
                const reader = new FileReader()
                reader.onload = () => resolve(reader.result as string)
                reader.readAsDataURL(file)
            })
        })

        const imageUrls = await Promise.all(imagePromises)

        const returnItems = 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

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

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

    const handleBackToStep1 = () => {
        setCurrentStep(1)
        setFormData(null)
        setImagePreviewUrls([])
    }

    const handleBackToStep2 = () => {
        setCurrentStep(2)
    }

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

    // Filter selected shipment items
    const selectedShipmentItems = allShipmentItems.filter(item =>
        selectedItems.includes(item._id)
    )

    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'>
                {/* Header */}
                <div className='mb-6'>
                    <div className='flex items-center justify-between mb-4'>
                        <h1 className='text-xl font-bold'>انتخاب کالاهای مرجوعی</h1>
                        <div className='text-sm text-gray-600'>شناسه سفارش: {order.results.order._id}</div>
                    </div>
                    <div className='border-t border-gray-200 mb-4'></div>

                    {/* Warning Message */}
                    <div className='flex items-start gap-3 p-4 bg-orange-50 border border-orange-200 rounded-lg mb-6'>
                        <div className='w-5 h-5 bg-orange-500 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5'>
                            <span className='text-white text-xs font-bold'>!</span>
                        </div>
                        <p className='text-sm text-gray-700 leading-relaxed'>
                            دقت کنید که برچسب سریال کالا (چسبیده روی بسته) را سالم نگه دارید و کالای اصلی را با تمام لوازم در بسته بندی اولیه قرار دهید
                        </p>
                    </div>
                </div>


                <div className='space-y-8'>
                    {currentStep === 1 && (
                        <>
                            <ProductSelection
                                items={allShipmentItems}
                                selectedItems={selectedItems}
                                onItemSelect={handleItemSelect}
                            />
                            <div className='flex gap-3 mt-8 justify-center'>
                                <Button
                                    onClick={() => router.back()}
                                    variant="outline"
                                    size="default"
                                >
                                    بازگشت
                                </Button>
                                <Button
                                    onClick={() => setCurrentStep(2)}
                                    disabled={selectedItems.length === 0}
                                    size="default"
                                >
                                    ادامه
                                </Button>
                            </div>
                        </>
                    )}

                    {currentStep === 2 && (
                        <ReturnForm
                            selectedItems={selectedShipmentItems}
                            onSubmit={handleFormSubmit}
                            onBack={handleBackToStep1}
                            isLoading={false}
                            returnReasons={returnReasons?.results.reasons || []}
                        />
                    )}

                    {currentStep === 3 && formData && (
                        <ReturnConfirmation
                            selectedItems={selectedShipmentItems}
                            quantities={formData.quantities}
                            reason={formData.reason}
                            description={formData.description}
                            images={formData.images}
                            imagePreviewUrls={imagePreviewUrls}
                            returnReasons={returnReasons?.results.reasons || []}
                            onSubmit={handleFinalSubmit}
                            onBack={handleBackToStep2}
                            isLoading={returnOrderMutation.isPending}
                        />
                    )}
                </div>
            </div>
        </Layout>
    )
}

export default ReturnPage