import type { Category } from '../types/category'
import { BlogCategoryRow } from './BlogCategoryRow'
import { getChildren, hasChildren } from '../utils/categories'
import styles from './CategoryTree.module.css'

interface BlogCategoryTreeProps {
  categories: Category[]
  expandedIds: Set<string>
  onToggle: (id: string) => void
  onAddSub: (id: string) => void
  onEdit: (id: string) => void
  onRemove: (id: string) => void
  parentId?: string | null
  depth?: number
}

export function BlogCategoryTree({
  categories,
  expandedIds,
  onToggle,
  onAddSub,
  onEdit,
  onRemove,
  parentId = null,
  depth = 0,
}: BlogCategoryTreeProps) {
  const nodes = getChildren(categories, parentId)

  return (
    <>
      {nodes.map((category) => {
        const childCount = hasChildren(categories, category.id)
        const expanded = expandedIds.has(category.id)

        return (
          <div key={category.id}>
            <BlogCategoryRow
              category={category}
              depth={depth}
              hasChildren={childCount}
              expanded={expanded}
              onToggle={() => onToggle(category.id)}
              onAddSub={onAddSub}
              onEdit={onEdit}
              onRemove={onRemove}
            />
            {childCount && (
              <div className={`${styles.childrenWrap} ${expanded ? styles.expanded : ''}`}>
                <div className={styles.childrenInner}>
                  <BlogCategoryTree
                    categories={categories}
                    expandedIds={expandedIds}
                    onToggle={onToggle}
                    onAddSub={onAddSub}
                    onEdit={onEdit}
                    onRemove={onRemove}
                    parentId={category.id}
                    depth={depth + 1}
                  />
                </div>
              </div>
            )}
          </div>
        )
      })}
    </>
  )
}
