"use client"

import { FC, useCallback, useMemo, useState } from 'react'
import { ArrowDown2 } from 'iconsax-react'
import { Category } from '@/types/products.types'
import { useRouter, usePathname, useSearchParams } from 'next/navigation'

type Props = {
    categories: Category[]
    selectedId: string | null
    onSelect: (id: string | null) => void
    categoryUrl?: string
}

const CategoryTree: FC<Props> = ({ categories, selectedId, onSelect, categoryUrl = 'Organic-supermarket' }) => {
    const router = useRouter()
    const roots = useMemo(() => categories || [], [categories])

    const findCategoryById = useCallback((cats: Category[], id: string): Category | null => {
        for (const cat of cats) {
            if (cat._id === id) return cat
            if (cat.children) {
                const found = findCategoryById(cat.children, id)
                if (found) return found
            }
        }
        return null
    }, [])

    const handleCategorySelect = useCallback((id: string | null) => {
        onSelect(id)
        // تغییر URL به دسته‌بندی انتخاب شده
        if (id) {
            const selectedCategory = findCategoryById(categories, id)
            if (selectedCategory) {
                // ساخت URL به فرمت products/Organic-supermarket?sort=1&page=1
                const categorySlug = selectedCategory.title_en.replace(/\s+/g, '-')
                const newUrl = `/products/${categorySlug}?sort=1&page=1`
                router.push(newUrl)
            }
        } else {
            // اگر هیچ دسته‌بندی انتخاب نشده، به دسته‌بندی فعلی برگرد
            const newUrl = `/products/${categoryUrl}?sort=1&page=1`
            router.push(newUrl)
        }
    }, [onSelect, router, categories, findCategoryById, categoryUrl])

    return (
        <div className='space-y-0'>
            {roots.map((cat) => (
                <Node key={cat._id} node={cat} selectedId={selectedId} onSelect={handleCategorySelect} depth={0} />
            ))}
        </div>
    )
}

type NodeProps = {
    node: Category
    selectedId: string | null
    onSelect: (id: string | null) => void
    depth: number
}

const Node: FC<NodeProps> = ({ node, selectedId, onSelect, depth }) => {
    const [open, setOpen] = useState<boolean>(false)
    const hasChildren = (node.children?.length ?? 0) > 0

    const toggle = useCallback(() => {
        if (hasChildren) {
            setOpen((p) => !p)
        } else {
            onSelect(node._id)
        }
    }, [hasChildren, node._id, onSelect])

    return (
        <div>
            <Row
                label={node.title_fa}
                isLeaf={!hasChildren}
                isSelected={selectedId === node._id}
                onClick={toggle}
                open={open}
                depth={depth}
            />
            {hasChildren && open && (
                <div className='mt-1.5 space-y-1.5'>
                    {node.children.map((child) => (
                        <Node
                            key={child._id}
                            node={child}
                            selectedId={selectedId}
                            onSelect={onSelect}
                            depth={depth + 1}
                        />
                    ))}
                </div>
            )}
        </div>
    )
}

type RowProps = {
    label: string
    isLeaf?: boolean
    isSelected?: boolean
    onClick: () => void
    open?: boolean
    depth?: number
}

const Row: FC<RowProps> = ({ label, isLeaf, isSelected, onClick, open, depth = 0 }) => {
    return (
        <button type='button' onClick={onClick} className='w-full'>
            <div
                className='flex items-center py-2 border-b border-border hover:bg-accent/40 rounded-md'
                style={{ paddingInlineStart: `${depth * 16}px` }}
            >
                <div className='ml-auto flex items-center gap-2.5'>
                    {!isLeaf && (
                        <ArrowDown2
                            size={16}
                            color='#6B7280'
                            className={`transition-transform ${open ? 'rotate-180' : ''}`}
                        />
                    )}
                    <span className={`text-[14px] leading-[22px] ${isSelected ? 'text-primary font-medium' : 'text-[#333333]'}`}>
                        {label}
                    </span>
                </div>
            </div>
        </button>
    )
}

export default CategoryTree


