import { useState, type FC } from 'react'
import { useGetFaq, useDeleteFaq } from './hooks/useSettingData'
import { FaqPageEnum } from './enum/Enum'
import { type FaqItem } from './types/Types'
import PageLoading from '../../components/PageLoading'
import Error from '../../components/Error'
import Td from '../../components/Td'
import Select from '../../components/Select'
import { Calendar, DocumentText, MessageQuestion, Add, Edit } from 'iconsax-react'
import Button from '../../components/Button'
import { Link, useNavigate } from 'react-router-dom'
import { Pages } from '@/config/Pages'
import TrashWithConfrim from '@/components/TrashWithConfrim'

const FaqList: FC = () => {
    const navigate = useNavigate()
    const [page, setPage] = useState<FaqPageEnum>(FaqPageEnum.Faq);
    const { data, isLoading, error, refetch } = useGetFaq(page);
    const deleteFaq = useDeleteFaq();

    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 faqItems = data?.results?.faqs || [];

    const formatDate = (dateString: string) => {
        if (!dateString) return '-';
        return new Date(dateString).toLocaleDateString('fa-IR');
    };

    const truncateText = (text: string, maxLength: number = 50) => {
        if (text.length <= maxLength) return text;
        return text.substring(0, maxLength) + '...';
    };

    const getPageName = (pageKey: string) => {
        const pageNames: Record<string, string> = {
            [FaqPageEnum.Faq]: 'سوالات متداول',
            [FaqPageEnum.Seller]: 'فروشندگان',
            [FaqPageEnum.ProductTag]: 'برچسب محصول',
            [FaqPageEnum.ProductDescription]: 'توضیحات محصول',
            [FaqPageEnum.ProductBenefit]: 'مزایای محصول',
            [FaqPageEnum.ShipmentProcess]: 'فرآیند ارسال',
            [FaqPageEnum.Policy]: 'سیاست‌ها',
        };
        return pageNames[pageKey] || pageKey;
    };

    const selectItems = Object.values(FaqPageEnum).map((pageValue) => ({
        value: pageValue,
        label: getPageName(pageValue),
    }));

    return (
        <div>
            <div className="flex justify-between items-center gap-4 mb-5">
                <div className='w-[200px]'>
                    <Select
                        className='w-full'
                        value={page}
                        onChange={(e) => setPage(e.target.value as FaqPageEnum)}
                        items={selectItems}
                        placeholder="انتخاب صفحه"
                    />
                </div>
                <Button
                    onClick={() => navigate(Pages.pages.faqCreate)}
                    className='w-fit'
                >
                    <div className='flex gap-2 items-center'>
                        <Add size={16} color='#fff' />
                        <span>افزودن سوال متداول</span>
                    </div>
                </Button>
            </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={'عملیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {faqItems.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={5} className="text-center py-8 text-gray-500">
                                    هیچ سوالی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            faqItems.map((item: FaqItem) => (
                                <tr key={item._id} className='tr'>
                                    <Td text="">
                                        <div className="flex items-center gap-2 max-w-xs">
                                            <MessageQuestion size={16} color="#8C90A3" />
                                            <span className="font-medium">{item.question}</span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="max-w-xs">
                                            <span className="text-gray-600 text-sm">
                                                {truncateText(item.answer)}
                                            </span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <DocumentText size={16} color="#8C90A3" />
                                            <span>{getPageName(item.page)}</span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Calendar size={16} color="#8C90A3" />
                                            <span>{formatDate(item.createdAt)}</span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Link to={`${Pages.pages.faqUpdate}${item._id}`}>
                                                <Edit size={16} color="#8C90A3" />
                                            </Link>
                                            <TrashWithConfrim
                                                onDelete={() => {
                                                    deleteFaq.mutate(item._id, {
                                                        onSuccess: () => {
                                                            refetch()
                                                        }
                                                    })
                                                }}
                                            />
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>
        </div>
    )
}

export default FaqList