import { type FC, useState } from 'react'
import PageTitle from '../../components/PageTitle'
import { useGetContactUs } from './hooks/useContactUsData';
import { type ContactUsItem } from './types';
import PageLoading from '../../components/PageLoading';
import Error from '../../components/Error';
import PaginationUi from '../../components/PaginationUi';
import Td from '../../components/Td';

const ContactUsList: FC = () => {
    const [currentPage, setCurrentPage] = useState(1);
    const { data: contactUsData, isLoading, error } = useGetContactUs(currentPage);

    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 contactUs = contactUsData?.results?.contactUs || [];
    const pager = contactUsData?.results?.pager;

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

    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={'پیام'} />
                        </tr>
                    </thead>
                    <tbody>
                        {contactUs.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={3} className="text-center py-8 text-gray-500">
                                    هیچ پیامی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            contactUs.map((contact: ContactUsItem, index: number) => (
                                <tr key={index} className='tr'>
                                    <Td text={contact.fullName} />
                                    <Td text={contact.email_phone} />
                                    <Td text={truncateText(contact.message)} />
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

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

export default ContactUsList