import { type FC, useState } from 'react'
import { useGetProductReviews, useApproveProductReview } from './hooks/useProductData'
import { type ProductReviewType } from './types/Types'
import PageLoading from '../../components/PageLoading'
import Error from '../../components/Error'
import PageTitle from '../../components/PageTitle'
import Td from '../../components/Td'
import PaginationUi from '../../components/PaginationUi'
import StatusWithText from '../../components/StatusWithText'
import { ReviewModal } from './components'
import Rate from 'rc-rate'
import { Eye } from 'iconsax-react'

const Reviews: FC = () => {
    const [currentPage, setCurrentPage] = useState(1);
    const [selectedReview, setSelectedReview] = useState<ProductReviewType | null>(null);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const { data, isLoading, error, refetch } = useGetProductReviews(currentPage);
    const approveMutation = useApproveProductReview();

    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 reviews = data?.results?.comments || [];
    const pager = data?.results?.pager;

    const getStatusVariant = (status: string) => {
        switch (status) {
            case 'accepted': return 'success';
            case 'rejected': return 'error';
            case 'pending': return 'warning';
            default: return 'warning';
        }
    };

    const getStatusText = (status: string) => {
        switch (status) {
            case 'accepted': return 'تایید شده';
            case 'rejected': return 'رد شده';
            case 'pending': return 'در انتظار';
            default: return status;
        }
    };

    const handleViewReview = (review: ProductReviewType) => {
        setSelectedReview(review);
        setIsModalOpen(true);
    };

    const handleCloseModal = () => {
        setIsModalOpen(false);
        setSelectedReview(null);
    };

    const handleApproveReview = async (reviewId: string) => {
        try {
            await approveMutation.mutateAsync(reviewId);
            await refetch();
            handleCloseModal();
        } catch (error) {
            console.error('خطا در تایید کامنت:', error);
        }
    };

    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>
                        {reviews.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={6} className="text-center py-8 text-gray-500">
                                    هیچ نظری یافت نشد
                                </td>
                            </tr>
                        ) : (
                            reviews.map((review: ProductReviewType) => (
                                <tr key={review._id} className='tr'>
                                    <Td text="">
                                        <div className="font-medium text-gray-900">
                                            {review.user?.[0]?.fullName || 'کاربر ناشناس'}
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-3">
                                            <div className="w-12 h-12 rounded-lg overflow-hidden">
                                                <img
                                                    src={review.product?.imagesUrl?.cover || '/placeholder-image.png'}
                                                    alt={review.product?.title_fa}
                                                    className="w-full h-full object-cover"
                                                />
                                            </div>
                                            <div>
                                                <div className="font-medium text-gray-900">
                                                    {review.product?.title_fa}
                                                </div>
                                                <div className="text-gray-500 text-xs">
                                                    {review.product?.title_en}
                                                </div>
                                            </div>
                                        </div>
                                    </Td>
                                    <Td text={review.title} />
                                    <Td text="">
                                        <Rate value={review.rate} disabled />
                                    </Td>
                                    <Td text="">
                                        <StatusWithText
                                            variant={getStatusVariant(review.status)}
                                            text={getStatusText(review.status)}
                                        />
                                    </Td>
                                    <Td text={review.createdAt} />
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Eye
                                                size={16}
                                                color="#8C90A3"
                                                className="cursor-pointer"
                                                onClick={() => handleViewReview(review)}
                                            />
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

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

            <ReviewModal
                isOpen={isModalOpen}
                onClose={handleCloseModal}
                review={selectedReview}
                onApprove={handleApproveReview}
                isApproving={approveMutation.isPending}
            />
        </div>
    )
}

export default Reviews