import { type FC, useState, useRef, useEffect } from 'react'
import { SearchNormal, ArrowDown2, ArrowUp2, Folder2, FolderOpen, DocumentText } from 'iconsax-react'
import { clx } from '../../../helpers/utils'
import Error from '../../../components/Error'
import { type CategoryTreeNode } from '../types/Types'

type Props = {
    className?: string
    label?: string
    placeholder?: string
    value: string
    onChange: (value: string) => void
    error_text?: string
    categories: CategoryTreeNode[]
    disabled?: boolean
}

const CategorySelect: FC<Props> = ({
    label,
    placeholder = 'انتخاب دسته',
    value,
    onChange,
    error_text,
    categories,
    disabled = false
}) => {
    const [isOpen, setIsOpen] = useState(false)
    const [searchTerm, setSearchTerm] = useState('')
    const [selectedCategory, setSelectedCategory] = useState<CategoryTreeNode | null>(null)
    const dropdownRef = useRef<HTMLDivElement>(null)

    // پیدا کردن دسته انتخاب شده بر اساس value
    useEffect(() => {
        if (value && categories.length > 0) {
            const findCategory = (cats: CategoryTreeNode[], id: string): CategoryTreeNode | null => {
                for (const cat of cats) {
                    if (cat._id === id) return cat
                    if (cat.children.length > 0) {
                        const found = findCategory(cat.children, id)
                        if (found) return found
                    }
                }
                return null
            }
            const found = findCategory(categories, value)
            setSelectedCategory(found)
        } else {
            setSelectedCategory(null)
        }
    }, [value, categories])

    // بستن dropdown با کلیک خارج از آن
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsOpen(false)
            }
        }

        document.addEventListener('mousedown', handleClickOutside)
        return () => document.removeEventListener('mousedown', handleClickOutside)
    }, [])

    // فیلتر کردن دسته‌ها بر اساس جستجو
    const filteredCategories = categories.filter(cat =>
        cat.title_fa.toLowerCase().includes(searchTerm.toLowerCase()) ||
        cat.title_en.toLowerCase().includes(searchTerm.toLowerCase())
    )

    // نمایش مسیر کامل دسته
    const getCategoryPath = (category: CategoryTreeNode): string => {
        const path: string[] = []
        let current: CategoryTreeNode | null = category

        while (current) {
            path.unshift(current.title_fa)
            if (current.parent) {
                const parent = categories.find(cat => cat._id === current?.parent)
                if (parent) {
                    current = parent
                } else {
                    // جستجو در children
                    const findParent = (cats: CategoryTreeNode[], id: string): CategoryTreeNode | null => {
                        for (const cat of cats) {
                            if (cat._id === id) return cat
                            if (cat.children.length > 0) {
                                const found = findParent(cat.children, id)
                                if (found) return found
                            }
                        }
                        return null
                    }
                    current = findParent(categories, current.parent)
                }
            } else {
                current = null
            }
        }

        return path.join(' > ')
    }

    // رندر کردن دسته‌ها به صورت درختی
    const renderCategoryTree = (cats: CategoryTreeNode[], level: number = 0) => {
        return cats.map(cat => (
            <div key={cat._id}>
                <div
                    className={clx(
                        'flex items-center gap-3 p-3 hover:bg-gray-50 cursor-pointer transition-colors rounded-lg',
                        level > 0 && 'mr-6',
                        cat._id === value && 'bg-blue-50 border border-blue-200'
                    )}
                    onClick={() => {
                        onChange(cat._id)
                        setIsOpen(false)
                        setSearchTerm('')
                    }}
                >
                    <div className="flex items-center gap-3 flex-1">
                        {/* آیکون دسته */}
                        <div className="flex-shrink-0">
                            {cat.children.length > 0 ? (
                                <FolderOpen size={20} className="text-blue-500" />
                            ) : (
                                <DocumentText size={20} className="text-gray-500" />
                            )}
                        </div>

                        {/* اطلاعات دسته */}
                        <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2">
                                <span className="text-sm font-medium text-gray-900">{cat.title_fa}</span>
                                {cat.children.length > 0 && (
                                    <span className="bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full text-xs">
                                        {cat.children.length}
                                    </span>
                                )}
                            </div>
                            <div className="text-xs text-gray-500 mt-0.5">
                                {cat.title_en}
                            </div>
                        </div>
                    </div>

                    {/* نشانگر انتخاب */}
                    {cat._id === value && (
                        <div className="flex-shrink-0">
                            <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                        </div>
                    )}
                </div>

                {/* نمایش زیردسته‌ها */}
                {cat.children.length > 0 && level < 2 && (
                    <div className="border-r border-gray-200 mr-6">
                        {renderCategoryTree(cat.children, level + 1)}
                    </div>
                )}
            </div>
        ))
    }

    return (
        <div className="w-full relative" ref={dropdownRef}>
            {label && (
                <label className="text-sm text-gray-700 mb-2 block font-medium">
                    {label}
                </label>
            )}

            {/* دکمه انتخاب */}
            <div
                className={clx(
                    'w-full border border-gray-300 rounded-xl bg-white cursor-pointer transition-all duration-200',
                    'hover:border-blue-400 hover:shadow-sm',
                    isOpen && 'border-blue-500 ring-2 ring-blue-100',
                    disabled && 'opacity-50 cursor-not-allowed bg-gray-50',
                    label && 'mt-1'
                )}
                onClick={() => !disabled && setIsOpen(!isOpen)}
            >
                <div className="flex items-center justify-between p-4">
                    <div className="flex-1 min-w-0">
                        {selectedCategory ? (
                            <div className="flex items-center gap-3">
                                <div className="flex-shrink-0">
                                    {selectedCategory.children.length > 0 ? (
                                        <FolderOpen size={20} className="text-blue-500" />
                                    ) : (
                                        <DocumentText size={20} className="text-gray-500" />
                                    )}
                                </div>
                                <div>
                                    <div className="text-sm font-medium text-gray-900">
                                        {selectedCategory.title_fa}
                                    </div>
                                    <div className="text-xs text-gray-500 mt-0.5">
                                        {getCategoryPath(selectedCategory)}
                                    </div>
                                </div>
                            </div>
                        ) : (
                            <div className="flex items-center gap-3">
                                <Folder2 size={20} className="text-gray-400" />
                                <span className="text-gray-400">{placeholder}</span>
                            </div>
                        )}
                    </div>

                    {!disabled && (
                        <div className="flex-shrink-0 ml-3">
                            {isOpen ? (
                                <ArrowUp2 size={16} className="text-gray-400" />
                            ) : (
                                <ArrowDown2 size={16} className="text-gray-400" />
                            )}
                        </div>
                    )}
                </div>
            </div>

            {/* Dropdown */}
            {isOpen && !disabled && (
                <div className="absolute z-50 w-full mt-2 bg-white border border-gray-200 rounded-xl shadow-lg max-h-80 overflow-hidden">
                    {/* جستجو */}
                    <div className="p-4 border-b border-gray-100 bg-gray-50">
                        <div className="relative">
                            <SearchNormal
                                size={18}
                                className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400"
                            />
                            <input
                                type="text"
                                placeholder="جستجو در دسته‌ها..."
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className="w-full pr-10 pl-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"
                            />
                        </div>
                    </div>

                    {/* لیست دسته‌ها */}
                    <div className="max-h-64 overflow-y-auto p-2">
                        {filteredCategories.length > 0 ? (
                            renderCategoryTree(filteredCategories)
                        ) : (
                            <div className="text-center py-8 text-gray-500">
                                <Folder2 size={32} className="mx-auto mb-2 text-gray-300" />
                                <p>دسته‌ای یافت نشد</p>
                            </div>
                        )}
                    </div>
                </div>
            )}

            {error_text && error_text !== '' && (
                <Error errorText={error_text} />
            )}
        </div>
    )
}

export default CategorySelect
