import { type FC } from 'react'
import { ArrowLeft2, Home } from 'iconsax-react'
import { type CategoryTreeNode } from '../types/Types'

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

const CategoryBreadcrumb: FC<Props> = ({
    category,
    categories,
    onNavigate,
    className = ''
}) => {
    // پیدا کردن مسیر کامل دسته
    const getCategoryPath = (cat: CategoryTreeNode): CategoryTreeNode[] => {
        const path: CategoryTreeNode[] = []
        let current: CategoryTreeNode | null = cat

        while (current) {
            path.unshift(current)
            if (current.parent) {
                const findParent = (cats: CategoryTreeNode[], id: string): CategoryTreeNode | null => {
                    for (const category of cats) {
                        if (category._id === id) return category
                        if (category.children.length > 0) {
                            const found = findParent(category.children, id)
                            if (found) return found
                        }
                    }
                    return null
                }
                current = findParent(categories, current.parent)
            } else {
                current = null
            }
        }

        return path
    }

    const path = getCategoryPath(category)

    return (
        <div className={`flex items-center gap-1 text-sm ${className}`}>
            <button
                onClick={() => onNavigate?.('')}
                className="flex items-center gap-2 px-3 py-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-all duration-200"
            >
                <Home size={16} />
                <span className="font-medium">خانه</span>
            </button>

            {path.map((cat, index) => (
                <div key={cat._id} className="flex items-center gap-1">
                    <ArrowLeft2 size={14} className="text-gray-300" />
                    <button
                        onClick={() => onNavigate?.(cat._id)}
                        className={`px-3 py-2 rounded-lg transition-all duration-200 font-medium ${index === path.length - 1
                                ? 'bg-blue-100 text-blue-700 border border-blue-200'
                                : 'text-gray-600 hover:text-gray-800 hover:bg-gray-100'
                            }`}
                    >
                        {cat.title_fa}
                    </button>
                </div>
            ))}
        </div>
    )
}

export default CategoryBreadcrumb
