import { type FC, useState } from 'react'
import PageTitle from '../../components/PageTitle'
import { useGetDocuments } from './hooks/useSettingData'
import { type DocumentTypeItem } from './types/Types'
import PageLoading from '../../components/PageLoading'
import Error from '../../components/Error'
import Td from '../../components/Td'
import { Calendar, DocumentText, TickCircle } from 'iconsax-react'
import Button from '@/components/Button'
import AddDocumentModal from './components/AddDocumentModal'

const ManageDocument: FC = () => {

    const { data: documents, isLoading, error } = useGetDocuments()

    // Modal states
    const [isModalOpen, setIsModalOpen] = useState(false)

    // Handlers
    const handleOpenModal = () => {
        setIsModalOpen(true)
    }

    const handleCloseModal = () => {
        setIsModalOpen(false)
    }

    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 documentItems = documents?.results?.documentTypes || [];

    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) + '...';
    };

    return (
        <div>
            <PageTitle />
            <div className='flex justify-end mt-5'>
                <Button
                    label='افزودن اسناد'
                    onClick={handleOpenModal}
                    className='w-fit'
                />
            </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={'تاریخ ایجاد'} />
                        </tr>
                    </thead>
                    <tbody>
                        {documentItems.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={5} className="text-center py-8 text-gray-500">
                                    هیچ سندی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            documentItems.map((item: DocumentTypeItem) => (
                                <tr key={item._id} className='tr'>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <DocumentText size={16} color="#8C90A3" />
                                            <span className="font-medium">{item.title}</span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="max-w-xs">
                                            <span className="text-gray-600 text-sm">
                                                {truncateText(item.description)}
                                            </span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <TickCircle
                                                size={16}
                                                color={item.required ? "#10B981" : "#EF4444"}
                                            />
                                            <span className={item.required ? "text-green-600" : "text-red-600"}>
                                                {item.required ? "ضروری" : "اختیاری"}
                                            </span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Calendar size={16} color="#8C90A3" />
                                            <span>{formatDate(item.createdAt)}</span>
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            {/* Add Document Modal */}
            <AddDocumentModal
                open={isModalOpen}
                onClose={handleCloseModal}
            />
        </div>
    )
}

export default ManageDocument