import { useState } from 'react'
import { AXIS_ICON, AXIS_LABEL, axisRowStats, axisValues } from './model.js'

export default function AxisColumn({ data, family, axis }) {
  const values = axisValues(data, family, axis)
  const tree = data.axis_trees?.[axis] || []
  const hasTree = tree.length > 0
  const [collapsed, setCollapsed] = useState(() => new Set())
  const familyItems = family.items || []
  const toggle = (path) => {
    setCollapsed((prev) => {
      const next = new Set(prev)
      if (next.has(path)) next.delete(path)
      else next.add(path)
      return next
    })
  }

  const renderFlatRow = (value, index) => {
    const stats = axisRowStats(familyItems, axis, value)
    const isMuted = stats.total === 0 && index > 8
    return (
      <div className={`axv ${isMuted ? 'muted' : ''}`} key={value}>
        <span className="tree-caret empty" />
        <span className="tree-label">{value}</span>
        <span className="tree-count">
          {stats.total > 0 && <b>{stats.total}</b>}
        </span>
      </div>
    )
  }

  const renderTreeNode = (node, level = 3) => {
    const children = node.children || []
    const childNames = children.map((child) => child.name)
    const stats = axisRowStats(familyItems, axis, [node.name, ...childNames])
    const isCollapsed = collapsed.has(node.path)
    const canExpand = level === 3 && children.length > 0
    return (
      <div className="tree-group" key={node.path}>
        <button
          className={`axv tree-node level-${level} ${stats.total === 0 ? 'muted' : ''}`}
          type="button"
          onClick={() => canExpand && toggle(node.path)}
        >
          <span className={`tree-caret ${canExpand ? '' : 'empty'}`}>
            {canExpand ? (isCollapsed ? '›' : '⌄') : ''}
          </span>
          <span className="tree-label">{node.name}</span>
          <span className="tree-count">
            {stats.total > 0 && <b>{stats.total}</b>}
          </span>
        </button>
        {canExpand && !isCollapsed && children.map((child) => {
          const childStats = axisRowStats(familyItems, axis, child.name)
          return (
            <div className={`axv tree-node level-4 ${childStats.total === 0 ? 'muted' : ''}`} key={child.path}>
              <span className="tree-caret empty" />
              <span className="tree-label">{child.name}</span>
              <span className="tree-count">
                {childStats.total > 0 && <b>{childStats.total}</b>}
              </span>
            </div>
          )
        })}
      </div>
    )
  }

  return (
    <div className="axcol">
      <div className="axhd">
        <div className="axis-title">
          <span className="axis-icon">{AXIS_ICON[axis] || axis.slice(0, 1)}</span>
          <span>{AXIS_LABEL[axis] || axis}</span>
        </div>
      </div>
      <div className="axlist">
        {hasTree ? tree.map((node) => renderTreeNode(node)) : values.map(renderFlatRow)}
      </div>
    </div>
  )
}
