import { type FC, useState } from 'react'
import { useGetProductReport } from './hooks/useReportData'
import { type Report } from './types/Types'
import PageLoading from '../../components/PageLoading'
import Error from '../../components/Error'
import Td from '../../components/Td'
import StatusWithText from '../../components/StatusWithText'
import DefaulModal from '../../components/DefaulModal'
import { Eye } from 'iconsax-react'
import Button from '@/components/Button'

const ProductReport: FC = () => {

    const { data, isLoading, error } = useGetProductReport();
    const [selectedReport, setSelectedReport] = useState<Report | null>(null);
    const [isModalOpen, setIsModalOpen] = useState(false);

    const openModal = (report: Report) => {
        setSelectedReport(report);
        setIsModalOpen(true);
    };

    const closeModal = () => {
        setIsModalOpen(false);
        setSelectedReport(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="خطا در بارگذاری گزارشات محصولات" />
            </div>
        );
    }

    const reports = data?.results?.reports || [];

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

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

    const formatDate = (dateString: string) => {
        return new Date(dateString).toLocaleDateString('fa-IR', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
        });
    };

    return (
        <div>
            <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>
                        {reports.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={7} className="text-center py-8 text-gray-500">
                                    هیچ گزارشی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            reports.map((report: Report) => (
                                <tr key={report._id} className='tr'>
                                    <Td text="">
                                        <div>
                                            <div className="font-medium text-gray-900">
                                                {report.user.fullName}
                                            </div>
                                            <div className="text-gray-500 text-xs">
                                                {report.user.phoneNumber}
                                            </div>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div>
                                            <div className="font-medium text-gray-900">
                                                {report.product.title_fa}
                                            </div>
                                            <div className="text-gray-500 text-xs">
                                                {report.product.title_en}
                                            </div>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex flex-wrap gap-1">
                                            {report.reason.slice(0, 2).map((reason) => (
                                                <span
                                                    key={reason._id}
                                                    className="inline-block bg-red-100 text-red-800 text-xs px-2 py-1 rounded-full"
                                                >
                                                    {reason.title}
                                                </span>
                                            ))}
                                            {report.reason.length > 2 && (
                                                <span className="inline-block bg-gray-100 text-gray-800 text-xs px-2 py-1 rounded-full">
                                                    +{report.reason.length - 2} دلیل دیگر
                                                </span>
                                            )}
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="max-w-xs truncate" title={report.description}>
                                            {report.description}
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <StatusWithText
                                            variant={getStatusVariant(report.status)}
                                            text={getStatusText(report.status)}
                                        />
                                    </Td>
                                    <Td text={formatDate(report.createdAt)} />
                                    <Td text="">
                                        <Button
                                            onClick={() => openModal(report)}
                                            className="h-8 text-xs w-fit"
                                            variant="outline"
                                        >
                                            <Eye color='#000' size={16} className="ml-1" />
                                            جزئیات
                                        </Button>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            <DefaulModal
                open={isModalOpen}
                close={closeModal}
                isHeader={true}
                title_header="جزئیات گزارش محصول"
                width={600}
            >
                {selectedReport && (
                    <div className="space-y-6">
                        {/* اطلاعات گزارش‌دهنده */}
                        <div className="bg-gray-50 p-4 rounded-xl">
                            <h3 className="text-lg font-semibold mb-3 text-gray-800">گزارش‌دهنده</h3>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-600">نام کامل</label>
                                    <p className="text-gray-900">{selectedReport.user.fullName}</p>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-600">شماره تلفن</label>
                                    <p className="text-gray-900">{selectedReport.user.phoneNumber}</p>
                                </div>
                                {selectedReport.user.nationalCode && (
                                    <div>
                                        <label className="block text-sm font-medium text-gray-600">کد ملی</label>
                                        <p className="text-gray-900">{selectedReport.user.nationalCode}</p>
                                    </div>
                                )}
                                {selectedReport.user.address && (
                                    <div className="md:col-span-2">
                                        <label className="block text-sm font-medium text-gray-600">آدرس</label>
                                        <p className="text-gray-900">{selectedReport.user.address}</p>
                                    </div>
                                )}
                            </div>
                        </div>

                        {/* اطلاعات محصول */}
                        <div className="bg-blue-50 p-4 rounded-xl">
                            <h3 className="text-lg font-semibold mb-3 text-gray-800">محصول گزارش‌شده</h3>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-600">عنوان فارسی</label>
                                    <p className="text-gray-900">{selectedReport.product.title_fa}</p>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-600">عنوان انگلیسی</label>
                                    <p className="text-gray-900">{selectedReport.product.title_en}</p>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-600">مدل</label>
                                    <p className="text-gray-900">{selectedReport.product.model}</p>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-600">برند</label>
                                    <p className="text-gray-900">{selectedReport.product.brand}</p>
                                </div>
                                {selectedReport.product.imagesUrl?.cover && (
                                    <div className="md:col-span-2">
                                        <label className="block text-sm font-medium text-gray-600 mb-2">تصویر محصول</label>
                                        <img
                                            src={selectedReport.product.imagesUrl.cover}
                                            alt={selectedReport.product.title_fa}
                                            className="w-24 h-24 object-cover rounded-lg"
                                        />
                                    </div>
                                )}
                            </div>
                        </div>

                        {/* دلایل گزارش */}
                        <div className="bg-red-50 p-4 rounded-xl">
                            <h3 className="text-lg font-semibold mb-3 text-gray-800">دلایل گزارش</h3>
                            <div className="flex flex-wrap gap-2">
                                {selectedReport.reason.map((reason) => (
                                    <span
                                        key={reason._id}
                                        className="inline-block bg-red-100 text-red-800 text-sm px-3 py-1 rounded-full"
                                    >
                                        {reason.title}
                                    </span>
                                ))}
                            </div>
                            {selectedReport.reason.some(r => r.placeholder) && (
                                <div className="mt-3">
                                    <label className="block text-sm font-medium text-gray-600 mb-2">توضیحات دلایل</label>
                                    <div className="space-y-2">
                                        {selectedReport.reason.filter(r => r.placeholder).map((reason) => (
                                            <p key={reason._id} className="text-sm text-gray-700 bg-white p-2 rounded">
                                                <strong>{reason.title}:</strong> {reason.placeholder}
                                            </p>
                                        ))}
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* توضیحات گزارش */}
                        <div className="bg-yellow-50 p-4 rounded-xl">
                            <h3 className="text-lg font-semibold mb-3 text-gray-800">توضیحات گزارش</h3>
                            <p className="text-gray-900 whitespace-pre-wrap">{selectedReport.description}</p>
                        </div>

                        {/* وضعیت و تاریخ */}
                        <div className="bg-green-50 p-4 rounded-xl">
                            <h3 className="text-lg font-semibold mb-3 text-gray-800">اطلاعات گزارش</h3>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-600">وضعیت</label>
                                    <StatusWithText
                                        variant={getStatusVariant(selectedReport.status)}
                                        text={getStatusText(selectedReport.status)}
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-600">تاریخ گزارش</label>
                                    <p className="text-gray-900">{formatDate(selectedReport.createdAt)}</p>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-600">تاریخ آخرین بروزرسانی</label>
                                    <p className="text-gray-900">{formatDate(selectedReport.updatedAt)}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
            </DefaulModal>
        </div>
    )
}

export default ProductReport