import { type FC, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import PageLoading from '../../components/PageLoading'
import Error from '../../components/Error'
import PaginationUi from '../../components/PaginationUi'
import PageTitle from '../../components/PageTitle'
import Td from '../../components/Td'
import { Eye } from 'iconsax-react'
import { Link } from 'react-router-dom'
import { type NativeOrderType } from '@/pages/orders/types/Types'
import { useGetNativeOrders } from '@/pages/orders/hooks/useOrderData'
import { Pages } from '@/config/Pages'

const STATUS_CONFIG = {
    Cancelled: { label: 'کنسل شده', color: 'bg-red-100 text-red-800' },
    wait_payment: { label: 'در انتظار پرداخت', color: 'bg-orange-100 text-orange-800' },
    process_by_sellers: { label: 'در حال پردازش توسط فروشنده', color: 'bg-blue-100 text-blue-800' },
    cancelled_system: { label: 'کنسل شده توسط سیستم', color: 'bg-red-100 text-red-800' },
    Delivered: { label: 'تحویل داده شده', color: 'bg-green-100 text-green-800' },
}

const getStatusLabel = (status: string): string => STATUS_CONFIG[status as keyof typeof STATUS_CONFIG]?.label || status

const getStatusColor = (status: string): string => {
    const statusConfig = STATUS_CONFIG[status as keyof typeof STATUS_CONFIG]
    return statusConfig && 'color' in statusConfig ? statusConfig.color : 'bg-gray-100 text-gray-800'
}

const Native: FC = () => {
    const [searchParams] = useSearchParams()
    const status = searchParams.get('status') || ''
    const [currentPage, setCurrentPage] = useState(1)

    const { data, isLoading, error } = useGetNativeOrders(currentPage, status)

    const orders = data?.results?.orders || []
    const pager = data?.results?.pager ? {
        ...data.results.pager,
        prevPage: data.results.pager.prevPage ? true : null,
        nextPage: data.results.pager.nextPage ? 'next' : null
    } : {
        page: 1,
        limit: 10,
        totalPages: 1,
        totalItems: 0,
        prevPage: null,
        nextPage: null
    }

    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={`خطا در بارگذاری ${getStatusLabel(status)}`} />
            </div>
        )
    }

    const getTableHeaders = () => {
        const headers = [
            'شماره سفارش',
            'مشتری',
            'مبلغ',
            'وضعیت'
        ]

        headers.push('تاریخ')
        headers.push('عملیات')

        return headers.map(header => <Td key={header} text={header} />)
    }

    const getTableRow = (order: NativeOrderType) => {
        const statusColor = getStatusColor(order.orderStatus)

        return (
            <tr key={order._id} className='tr'>
                <Td text={`#${order._id}`} />
                <Td text={order.user?.fullName || 'نامشخص'} />
                <Td text={(order.payment?.totalPrice || 0).toLocaleString('fa-IR')} />
                <Td text="">
                    <span className={`px-2 py-1 rounded-full text-xs ${statusColor}`}>
                        {getStatusLabel(order.orderStatus)}
                    </span>
                </Td>
                <Td text={order.createdAt || 'نامشخص'} />
                <Td text="">
                    <div className="flex items-center gap-2">
                        <Link to={`${Pages.orders.detailUser}${order._id}`}>
                            <Eye color='#8C90A3' size={16} className="cursor-pointer hover:text-blue-500 transition-colors" />
                        </Link>
                    </div>
                </Td>
            </tr>
        )
    }

    const columnCount = 6

    return (
        <div className="space-y-6">
            <PageTitle />
            <h1 className="text-2xl font-bold">{getStatusLabel(status)}</h1>

            <div className='relative overflow-x-auto rounded-3xl bg-white shadow-sm'>
                <table className='w-full text-sm'>
                    <thead className='thead'>
                        <tr>
                            {getTableHeaders()}
                        </tr>
                    </thead>
                    <tbody>
                        {orders.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={columnCount} className="text-center py-12 text-gray-500">
                                    هیچ سفارشی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            orders.map(order => getTableRow(order))
                        )}
                    </tbody>
                </table>
            </div>

            {orders.length > 0 && (
                <PaginationUi
                    pager={pager}
                    onPageChange={setCurrentPage}
                />
            )}
        </div>
    )
}

export default Native
