import { type FC, useState } from 'react'
import { useGetProductQuestions, useApproveProductQuestion, useAnswerProductQuestion } from './hooks/useProductData'
import { type ProductQuestionType } 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 { QuestionModal } from './components'
import { Eye } from 'iconsax-react'

const Questions: FC = () => {
    const [currentPage, setCurrentPage] = useState(1);
    const [selectedQuestion, setSelectedQuestion] = useState<ProductQuestionType | null>(null);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const { data, isLoading, error, refetch } = useGetProductQuestions(currentPage);
    const approveMutation = useApproveProductQuestion();
    const answerMutation = useAnswerProductQuestion();

    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 questions = data?.results?.questions || [];
    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 handleViewQuestion = (question: ProductQuestionType) => {
        setSelectedQuestion(question);
        setIsModalOpen(true);
    };

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

    const handleApproveQuestion = async (questionId: string) => {
        try {
            await approveMutation.mutateAsync(questionId);
            await refetch();
            handleCloseModal();
        } catch (error) {
            console.error('خطا در تایید سوال:', error);
        }
    };

    const handleAnswerQuestion = async (questionId: string, answer: string) => {
        try {
            await answerMutation.mutateAsync({ id: questionId, answer });
            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={'عملیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {questions.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={6} className="text-center py-8 text-gray-500">
                                    هیچ سوالی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            questions.map((question: ProductQuestionType) => (
                                <tr key={question._id} className='tr'>
                                    <Td text="">
                                        <div className="font-medium text-gray-900">
                                            {question.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={question.product?.imagesUrl?.cover || '/placeholder-image.png'}
                                                    alt={question.product?.title_fa}
                                                    className="w-full h-full object-cover"
                                                />
                                            </div>
                                            <div>
                                                <div className="font-medium text-gray-900">
                                                    {question.product?.title_fa}
                                                </div>
                                                <div className="text-gray-500 text-xs">
                                                    {question.product?.title_en}
                                                </div>
                                            </div>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="max-w-xs truncate">
                                            {question.content}
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <StatusWithText
                                            variant={getStatusVariant(question.status)}
                                            text={getStatusText(question.status)}
                                        />
                                    </Td>
                                    <Td text={question.createdAt} />
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Eye
                                                size={16}
                                                color="#8C90A3"
                                                className="cursor-pointer"
                                                onClick={() => handleViewQuestion(question)}
                                            />
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

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

            <QuestionModal
                isOpen={isModalOpen}
                onClose={handleCloseModal}
                question={selectedQuestion}
                onApprove={handleApproveQuestion}
                onAnswer={handleAnswerQuestion}
                isApproving={approveMutation.isPending}
                isAnswering={answerMutation.isPending}
            />
        </div>
    )
}

export default Questions