import { type FC, useState } from 'react'
import { ArrowDown2, ArrowRight2, Folder2, FolderOpen, DocumentText } from 'iconsax-react'
import { type CategoryTreeNode } from '../types/Types'

type Props = {
    categories: CategoryTreeNode[]
    onSelect?: (category: CategoryTreeNode) => void
    selectedId?: string
    className?: string
}

const CategoryTree: FC<Props> = ({
    categories,
    onSelect,
    selectedId,
    className = ''
}) => {
    const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set())

    const toggleNode = (nodeId: string) => {
        const newExpanded = new Set(expandedNodes)
        if (newExpanded.has(nodeId)) {
            newExpanded.delete(nodeId)
        } else {
            newExpanded.add(nodeId)
        }
        setExpandedNodes(newExpanded)
    }

    const renderCategoryNode = (category: CategoryTreeNode, level: number = 0) => {
        const isExpanded = expandedNodes.has(category._id)
        const hasChildren = category.children.length > 0
        const isSelected = selectedId === category._id

        return (
            <div key={category._id} className="select-none">
                <div
                    className={`
            flex items-center gap-3 p-3 rounded-xl cursor-pointer transition-all duration-200
            hover:bg-gray-50 hover:shadow-sm
            ${isSelected ? 'bg-blue-50 border border-blue-200 shadow-sm' : ''}
            ${level > 0 ? 'mr-6' : ''}
          `}
                    style={{ paddingLeft: `${level * 24 + 16}px` }}
                    onClick={() => onSelect?.(category)}
                >
                    {/* دکمه گسترش */}
                    {hasChildren && (
                        <button
                            onClick={(e) => {
                                e.stopPropagation()
                                toggleNode(category._id)
                            }}
                            className="p-1.5 hover:bg-gray-200 rounded-lg transition-colors flex-shrink-0"
                        >
                            {isExpanded ? (
                                <ArrowDown2 size={16} className="text-gray-600" />
                            ) : (
                                <ArrowRight2 size={16} className="text-gray-600" />
                            )}
                        </button>
                    )}

                    {/* فاصله برای دسته‌های بدون فرزند */}
                    {!hasChildren && <div className="w-8" />}

                    {/* آیکون دسته */}
                    <div className="flex-shrink-0">
                        {hasChildren ? (
                            isExpanded ? (
                                <FolderOpen size={20} className="text-blue-500" />
                            ) : (
                                <Folder2 size={20} className="text-gray-500" />
                            )
                        ) : (
                            <DocumentText size={20} className="text-gray-500" />
                        )}
                    </div>

                    {/* اطلاعات دسته */}
                    <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                            <span className={`text-sm font-medium ${isSelected ? 'text-blue-700' : 'text-gray-900'}`}>
                                {category.title_fa}
                            </span>

                            {hasChildren && (
                                <span className="bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full text-xs font-medium">
                                    {category.children.length}
                                </span>
                            )}

                            {category.leaf && (
                                <span className="bg-green-100 text-green-700 px-2 py-0.5 rounded-full text-xs">
                                    نهایی
                                </span>
                            )}
                        </div>

                        <div className="text-xs text-gray-500">
                            {category.title_en}
                        </div>

                        {category.description && (
                            <div className="text-xs text-gray-400 mt-1 line-clamp-1">
                                {category.description}
                            </div>
                        )}
                    </div>

                    {/* نشانگر انتخاب */}
                    {isSelected && (
                        <div className="flex-shrink-0">
                            <div className="w-3 h-3 bg-blue-500 rounded-full shadow-sm"></div>
                        </div>
                    )}
                </div>

                {/* نمایش زیردسته‌ها */}
                {hasChildren && isExpanded && (
                    <div className="border-r-2 border-gray-200 mr-6">
                        {category.children.map(child => renderCategoryNode(child, level + 1))}
                    </div>
                )}
            </div>
        )
    }

    if (categories.length === 0) {
        return (
            <div className={`text-center py-12 text-gray-500 ${className}`}>
                <Folder2 size={48} className="mx-auto mb-4 text-gray-300" />
                <p className="text-lg font-medium text-gray-400 mb-2">دسته‌ای موجود نیست</p>
                <p className="text-sm text-gray-400">برای شروع، دسته‌ای جدید ایجاد کنید</p>
            </div>
        )
    }

    return (
        <div className={`space-y-2 ${className}`}>
            {categories.map(category => renderCategoryNode(category))}
        </div>
    )
}

export default CategoryTree
