import { type FC, useState, type ReactElement } from 'react'
import PageTitle from '@/components/PageTitle'
import { useGetBlogCategories, useDeleteBlogCategory } from './hooks/useBlogsData'
import { type BlogCategory } from './types/Types'
import PageLoading from '@/components/PageLoading'
import Error from '@/components/Error'
import Td from '@/components/Td'
import TrashWithConfrim from '@/components/TrashWithConfrim'
import { Edit, ArrowDown2, ArrowLeft2 } from 'iconsax-react'
import Button from '@/components/Button'
import { useQueryClient } from '@tanstack/react-query'
import { toast } from 'react-toastify'
import { extractErrorMessage } from '@/helpers/utils'
import { CategoryModal } from './components'

const BlogCategoryList: FC = () => {
    const queryClient = useQueryClient()
    const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
    const [isUpdateModalOpen, setIsUpdateModalOpen] = useState(false)
    const [selectedCategory, setSelectedCategory] = useState<BlogCategory | null>(null)
    const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())

    const { data: categoriesData, isLoading, error } = useGetBlogCategories()
    const deleteCategoryMutation = useDeleteBlogCategory()

    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 handleDeleteCategory = (categoryId: string) => {
        deleteCategoryMutation.mutate(categoryId, {
            onSuccess: () => {
                toast.success('دسته‌بندی با موفقیت حذف شد')
                queryClient.invalidateQueries({ queryKey: ['blog-categories'] })
            },
            onError: (error) => {
                toast.error(extractErrorMessage(error))
            }
        })
    }

    const handleEditCategory = (category: BlogCategory) => {
        setSelectedCategory(category)
        setIsUpdateModalOpen(true)
    }

    const handleCloseUpdateModal = () => {
        setIsUpdateModalOpen(false)
        setSelectedCategory(null)
    }

    const toggleExpand = (categoryId: string) => {
        setExpandedCategories(prev => {
            const newSet = new Set(prev)
            if (newSet.has(categoryId)) {
                newSet.delete(categoryId)
            } else {
                newSet.add(categoryId)
            }
            return newSet
        })
    }

    const categories = categoriesData?.results?.categories || []

    // تابع بازگشتی برای رندر کردن دسته‌بندی‌ها به صورت درختی
    const renderCategory = (category: BlogCategory, level: number = 0): ReactElement[] => {
        const hasChildren = category.children && category.children.length > 0
        const isExpanded = expandedCategories.has(category._id)

        const categoryRow = (
            <tr key={category._id} className='tr'>
                <Td text="">
                    <div className="flex items-center gap-2" style={{ paddingRight: `${level * 24}px` }}>
                        {hasChildren && (
                            <button
                                onClick={() => toggleExpand(category._id)}
                                className="hover:bg-gray-100 rounded p-1"
                            >
                                {isExpanded ? (
                                    <ArrowDown2 size={16} color='#8C90A3' />
                                ) : (
                                    <ArrowLeft2 size={16} color='#8C90A3' />
                                )}
                            </button>
                        )}
                        {!hasChildren && <div className="w-6"></div>}
                        <span>{category.title_fa}</span>
                    </div>
                </Td>
                <Td text={category.slug} />
                <Td text="">
                    <div className="max-w-xs truncate">
                        {category.description || '-'}
                    </div>
                </Td>
                <Td text="">
                    <div className="flex items-center gap-2">
                        <button onClick={() => handleEditCategory(category)}>
                            <Edit
                                color='#8C90A3'
                                size={16}
                                className="cursor-pointer hover:text-blue-500"
                            />
                        </button>

                        <TrashWithConfrim
                            onDelete={() => handleDeleteCategory(category._id)}
                            isLoading={deleteCategoryMutation.isPending}
                        />
                    </div>
                </Td>
            </tr>
        )

        const rows = [categoryRow]

        // اگر دسته‌بندی فرزند دارد و باز شده است، آن‌ها را هم نمایش بده
        if (hasChildren && isExpanded) {
            category.children.forEach(child => {
                rows.push(...renderCategory(child, level + 1))
            })
        }

        return rows
    }

    // رندر همه دسته‌بندی‌های اصلی
    const renderAllCategories = () => {
        if (categories.length === 0) {
            return (
                <tr className='tr'>
                    <td colSpan={5} className="text-center py-8 text-gray-500">
                        هیچ دسته‌بندی یافت نشد
                    </td>
                </tr>
            )
        }

        const allRows: ReactElement[] = []
        categories.forEach(category => {
            allRows.push(...renderCategory(category))
        })
        return allRows
    }

    return (
        <div>
            <PageTitle />
            <div className='flex justify-end mt-5'>
                <Button
                    label='افزودن دسته‌بندی'
                    onClick={() => setIsCreateModalOpen(true)}
                    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>
                        {renderAllCategories()}
                    </tbody>
                </table>
            </div>

            <CategoryModal
                open={isCreateModalOpen}
                close={() => setIsCreateModalOpen(false)}
                mode="create"
            />

            <CategoryModal
                open={isUpdateModalOpen}
                close={handleCloseUpdateModal}
                mode="update"
                category={selectedCategory}
            />
        </div>
    )
}

export default BlogCategoryList
