import PageTitle from '@/components/PageTitle'
import { type FC, useState } from 'react'
import { useGetCancels } 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 CancelOrderType } from '@/pages/orders/types/Types'
import { Eye } from 'iconsax-react'
import CancelItemsModal from '@/pages/orders/components/CancelItemsModal'
import { type PagerType as ProductPagerType } from '@/pages/products/types/Types'

const Cancels: FC = () => {
    const [currentPage, setCurrentPage] = useState(1)
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [selectedCancel, setSelectedCancel] = useState<CancelOrderType | null>(null)
    const { data, isLoading, error } = useGetCancels(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 cancelsOrders = data?.results?.cancelsOrders || []
    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
        }
    }

    const handleEyeClick = (cancel: CancelOrderType) => {
        setSelectedCancel(cancel)
        setIsModalOpen(true)
    }

    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={'تعداد'} />
                            <Td text={'جزئیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {cancelsOrders.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={8} className='text-center py-8 text-muted-foreground'>
                                    کنسلی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            cancelsOrders.map((cancel: CancelOrderType) => {
                                const totalQuantity = cancel?.cancelOrderItems?.quantity || 0
                                const orderId = cancel?.order?._id || null
                                const productName = cancel?.cancelOrderItems?.shipmentItem?.product?.title_fa || '-'
                                const cancellerName = cancel?.cancellerDetails?.fullName || '-'

                                return (
                                    <tr key={cancel._id} className='tr'>
                                        <Td text={orderId ? `#${orderId}` : '-'} />
                                        <Td text={cancellerName} />
                                        <Td text={productName} />
                                        <Td text=''>
                                            <StatusWithText
                                                variant={getStatusVariant(cancel?.status)}
                                                text={getStatusText(cancel?.status)}
                                            />
                                        </Td>
                                        <Td text={`${formatPrice(Number(cancel?.total_price || 0))} تومان`} />
                                        <Td text={formatDateShort(cancel?.createdAt)} />
                                        <Td text={String(totalQuantity)} />
                                        <Td text="">
                                            <button
                                                onClick={() => handleEyeClick(cancel)}
                                                className="cursor-pointer hover:opacity-70 transition-opacity"
                                            >
                                                <Eye size={16} color="#4B5563" />
                                            </button>
                                        </Td>
                                    </tr>
                                )
                            })
                        )}
                    </tbody>
                </table>
            </div>

            <PaginationUi
                pager={pager ? {
                    ...pager,
                    nextPage: pager.nextPage ? String(pager.nextPage) : null,
                } as ProductPagerType : null}
                onPageChange={(page) => setCurrentPage(page)}
            />

            <CancelItemsModal
                open={isModalOpen}
                close={() => { setIsModalOpen(false); setSelectedCancel(null); }}
                data={selectedCancel}
            />
        </div>
    )
}

export default Cancels