import { type FC, useState } from 'react'
import { useDeleteBlog, useGetBlogs } from './hooks/useBlogsData'
import { useQueryClient } from '@tanstack/react-query'
import { type Blog } from './types/Types'
import PageLoading from '../../components/PageLoading'
import Error from '../../components/Error'
import PaginationUi from '../../components/PaginationUi'
import Td from '../../components/Td'
import TrashWithConfrim from '../../components/TrashWithConfrim'
import { Edit, Eye } from 'iconsax-react'
import { Link, useNavigate } from 'react-router-dom'
import { Pages } from '@/config/Pages'
import Button from '@/components/Button'

const BlogsList: FC = () => {

    const navigate = useNavigate()
    const queryClient = useQueryClient()
    const [currentPage, setCurrentPage] = useState(1)
    const deleteBlog = useDeleteBlog()
    const { data: blogsData, isLoading, error } = useGetBlogs(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 blogs = blogsData?.blogs || []
    const pager = blogsData?.pager

    return (
        <div>
            <div className='flex justify-end mt-5'>
                <Button
                    label='افزودن بلاگ'
                    onClick={() => navigate(`${Pages.blog.create}`)}
                    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={'نویسنده'} />
                            <Td text={'بازدید'} />
                            <Td text={'تاریخ ایجاد'} />
                            <Td text={'عملیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {blogs.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={7} className="text-center py-8 text-gray-500">
                                    هیچ بلاگی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            blogs.map((blog: Blog) => (
                                <tr key={blog._id} className='tr'>
                                    <Td text="">
                                        <div className="w-12 h-12 rounded-lg overflow-hidden">
                                            <img
                                                src={blog.imageUrl || '/placeholder-image.png'}
                                                alt={blog.title_fa}
                                                className="w-full h-full object-cover"
                                            />
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div>
                                            <div className="font-medium text-gray-900">
                                                {blog.title_fa}
                                            </div>
                                            <div className="text-gray-500 text-xs">
                                                {blog.slug}
                                            </div>
                                        </div>
                                    </Td>
                                    <Td text={blog.category.title_fa} />
                                    <Td text={blog.author.fullName} />
                                    <Td text="">
                                        <div className="flex items-center gap-1">
                                            <Eye size={14} className="text-gray-400" />
                                            <span>{blog.view.toLocaleString('fa-IR')}</span>
                                        </div>
                                    </Td>
                                    <Td text={blog.createdAt} />
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Link to={`${Pages.blog.detail}${blog._id}`}>
                                                <Edit color='#8C90A3' size={16} className="cursor-pointer hover:text-blue-500" />
                                            </Link>

                                            <TrashWithConfrim
                                                onDelete={() => {
                                                    deleteBlog.mutate(blog._id, {
                                                        onSuccess: () => {
                                                            queryClient.invalidateQueries({ queryKey: ['blogs'] })
                                                        }
                                                    })
                                                }}
                                            />
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

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

export default BlogsList