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

interface CategoryTreeProps {
  categories: Category[]
  expandedIds: Set<string>
  variationCounts: Record<string, number>
  technicalFieldCounts: Record<string, number>
  onToggle: (id: string) => void
  onAddSub: (id: string) => void
  onVariations: (id: string) => void
  onTechnicalForm: (id: string) => void
  onOptions: (id: string) => void
  onRemove: (id: string) => void
  parentId?: string | null
  depth?: number
}

export function CategoryTree({
  categories,
  expandedIds,
  variationCounts,
  technicalFieldCounts,
  onToggle,
  onAddSub,
  onVariations,
  onTechnicalForm,
  onOptions,
  onRemove,
  parentId = null,
  depth = 0,
}: CategoryTreeProps) {
  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}>
            <CategoryRow
              category={category}
              depth={depth}
              hasChildren={childCount}
              expanded={expanded}
              variationCount={variationCounts[category.id] ?? category.variationCount ?? 0}
              technicalFieldCount={technicalFieldCounts[category.id] ?? 0}
              onToggle={() => onToggle(category.id)}
              onAddSub={onAddSub}
              onVariations={onVariations}
              onTechnicalForm={onTechnicalForm}
              onOptions={onOptions}
              onRemove={onRemove}
            />
            {childCount && (
              <div className={`${styles.childrenWrap} ${expanded ? styles.expanded : ''}`}>
                <div className={styles.childrenInner}>
                  <CategoryTree
                    categories={categories}
                    expandedIds={expandedIds}
                    variationCounts={variationCounts}
                    technicalFieldCounts={technicalFieldCounts}
                    onToggle={onToggle}
                    onAddSub={onAddSub}
                    onVariations={onVariations}
                    onTechnicalForm={onTechnicalForm}
                    onOptions={onOptions}
                    onRemove={onRemove}
                    parentId={category.id}
                    depth={depth + 1}
                  />
                </div>
              </div>
            )}
          </div>
        )
      })}
    </>
  )
}
