import PageTitle from '@/components/PageTitle'
import { type FC, useState } from 'react'
import { useGetOrderReturns } from './hooks/useOrderData'
import PageLoading from '@/components/PageLoading'
import Error from '@/components/Error'
import PaginationUi from '@/components/PaginationUi'
import Td from '@/components/Td'
import StatusWithText from '@/components/StatusWithText'
import { formatDateShort, formatPrice } from '@/helpers/func'
import { type ReturnOrderType } from '@/pages/orders/types/ReturnTypes'
import { Eye } from 'iconsax-react'
import ReturnItemsModal from '@/pages/orders/components/ReturnItemsModal'
import { Link } from 'react-router-dom'
import { Pages } from '@/config/Pages'

const Returns: FC = () => {
    const [currentPage, setCurrentPage] = useState(1)
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [selectedReturn, setSelectedReturn] = useState<ReturnOrderType | null>(null)
    const { data, isLoading, error } = useGetOrderReturns(currentPage)

    if (isLoading) {
        return (
            <div className="flex justify-center items-center min-h-[400px]">
                <PageLoading />
            </div>
        )
    }

    if (error) {
        return (
            <div className="flex justify-center items-center min-h-[400px]">
                <Error errorText="خطا در بارگذاری مرجوعی‌ها" />
            </div>
        )
    }

    const returnsOrders = data?.results?.returnsOrders || []
    const pager = data?.results?.pager

    const getStatusVariant = (status: string) => {
        switch (status) {
            case 'Approved': return 'success'
            case 'Completed': return 'success'
            case 'Rejected': return 'error'
            case 'Pending':
            default: return 'warning'
        }
    }

    const getStatusText = (status: string) => {
        switch (status) {
            case 'Approved': return 'تایید شده'
            case 'Completed': return 'تکمیل شده'
            case 'Rejected': return 'رد شده'
            case 'Pending': return 'در انتظار'
            default: return status
        }
    }

    return (
        <div>
            <PageTitle title1='مرجوعی ها' />

            <div className='relative overflow-x-auto rounded-3xl mt-5 w-full'>
                <table className='w-full text-sm'>
                    <thead className='thead'>
                        <tr>
                            <Td text={'شماره سفارش'} />
                            <Td text={'فروشگاه'} />
                            <Td text={'وضعیت'} />
                            <Td text={'مبلغ کل'} />
                            <Td text={'تاریخ ثبت'} />
                            <Td text={'تعداد اقلام'} />
                            <Td text={'جزئیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {returnsOrders.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={7} className='text-center py-8 text-muted-foreground'>
                                    مرجوعی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            returnsOrders.map((ret: ReturnOrderType) => {
                                const totalQuantity = Array.isArray(ret?.returnOrderItems)
                                    ? ret.returnOrderItems.reduce((sum, item) => sum + (item?.quantity || 0), 0)
                                    : 0

                                return (
                                    <tr key={ret._id} className='tr'>
                                        <Td text={`#${ret?.order?._id ?? '-'}`} />
                                        <Td text={ret?.shopName ?? '-'} />
                                        <Td text=''>
                                            <StatusWithText
                                                variant={getStatusVariant(ret?.status)}
                                                text={getStatusText(ret?.status)}
                                            />
                                        </Td>
                                        <Td text={`${formatPrice(Number(ret?.total_price || 0))} تومان`} />
                                        <Td text={formatDateShort(ret?.createdAt)} />
                                        <Td text={String(totalQuantity)} />
                                        <Td text="">

                                            <Link to={`${Pages.orders.returnDetails}${ret._id}`}>
                                                <Eye size={16} color="#4B5563" />
                                            </Link>
                                        </Td>
                                    </tr>
                                )
                            })
                        )}
                    </tbody>
                </table>
            </div>

            <PaginationUi
                pager={pager}
                onPageChange={(page) => setCurrentPage(page)}
            />

            <ReturnItemsModal
                open={isModalOpen}
                close={() => { setIsModalOpen(false); setSelectedReturn(null); }}
                data={selectedReturn}
            />
        </div>
    )
}

export default Returns