import { type FC, useState } from 'react'
import PageTitle from '../../components/PageTitle'
import { useApproveWholesaleRequest, useGetWholesaleRequests } from './hooks/useSellerData'
import { type WholesaleRequest } from './types/Types'
import { type PagerType } from '../products/types/Types'
import PageLoading from '../../components/PageLoading'
import Error from '../../components/Error'
import PaginationUi from '../../components/PaginationUi'
import Td from '../../components/Td'
import WholesaleRequestTableRow from './components/WholesaleRequestTableRow'
import { toast } from 'react-toastify'
import { extractErrorMessage } from '@/helpers/utils'

const WholeSaleRequest: FC = () => {
    const [currentPage, setCurrentPage] = useState(1);
    const { data: wholesaleData, isLoading, error, refetch } = useGetWholesaleRequests(currentPage);
    const approveWholesaleRequestMutation = useApproveWholesaleRequest();

    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 handleApprove = async (id: string) => {
        await approveWholesaleRequestMutation.mutateAsync(id, {
            onSuccess: () => {
                refetch();
                toast.success('درخواست با موفقیت تایید شد');
            },
            onError: (error) => {
                toast.error(extractErrorMessage(error));
            }
        });
    };

    const requests = wholesaleData?.results?.requests || [];
    const pager = wholesaleData?.results?.pager;

    return (
        <div>
            <PageTitle />
            <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>
                        {requests.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={7} className="text-center py-8 text-gray-500">
                                    هیچ درخواست عمده‌فروشی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            requests.map((request: WholesaleRequest) => (
                                <WholesaleRequestTableRow
                                    key={request._id}
                                    request={request}
                                    onApprove={handleApprove}
                                />
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            <PaginationUi
                pager={pager as unknown as PagerType}
                onPageChange={(page) => {
                    setCurrentPage(page);
                }}
            />
        </div>
    )
}

export default WholeSaleRequest