import { useMemo, useState } from 'react'
import { ChevronRight, FolderTree } from 'lucide-react'
import { useProductGroups } from '@/lib/useLookups'
import type { ProductGroup } from '@/lib/types'

interface TreeNode {
  group: ProductGroup
  children: TreeNode[]
  productCount?: number
}

function buildTree(groups: ProductGroup[]): TreeNode[] {
  const byId = new Map<string, TreeNode>()
  groups.forEach((g) => byId.set(g.id, { group: g, children: [] }))
  const roots: TreeNode[] = []
  byId.forEach((node) => {
    if (node.group.parentId && byId.has(node.group.parentId)) {
      byId.get(node.group.parentId)!.children.push(node)
    } else {
      roots.push(node)
    }
  })
  const sortRec = (nodes: TreeNode[]) => {
    nodes.sort((a, b) => (a.group.sortOrder - b.group.sortOrder) || a.group.name.localeCompare(b.group.name, 'ru'))
    nodes.forEach((n) => sortRec(n.children))
  }
  sortRec(roots)
  return roots
}

interface Props {
  selectedId: string | null
  onSelect: (id: string | null) => void
}

export function ProductGroupTree({ selectedId, onSelect }: Props) {
  const { data: groups, isLoading } = useProductGroups()
  const tree = useMemo(() => buildTree(groups ?? []), [groups])
  const [expanded, setExpanded] = useState<Set<string>>(new Set())

  const toggle = (id: string) =>
    setExpanded((prev) => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })

  const renderNode = (node: TreeNode, depth: number) => {
    const hasChildren = node.children.length > 0
    const isOpen = expanded.has(node.group.id)
    const isActive = selectedId === node.group.id
    return (
      <div key={node.group.id}>
        <div
          className={
            'flex items-center gap-1 text-sm rounded cursor-pointer select-none pr-2 hover:bg-slate-100 dark:hover:bg-slate-800 ' +
            (isActive ? 'bg-emerald-50 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-200 font-medium' : '')
          }
          style={{ paddingLeft: 4 + depth * 12 }}
        >
          {hasChildren ? (
            <button
              type="button"
              onClick={(e) => { e.stopPropagation(); toggle(node.group.id) }}
              className="p-0.5 text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
              aria-label={isOpen ? 'Свернуть' : 'Развернуть'}
            >
              <ChevronRight className={'w-3.5 h-3.5 transition-transform ' + (isOpen ? 'rotate-90' : '')} />
            </button>
          ) : (
            <span className="w-[18px]" />
          )}
          <button
            type="button"
            onClick={() => onSelect(node.group.id)}
            className="flex-1 text-left py-1 truncate"
            title={node.group.path}
          >
            {node.group.name}
          </button>
        </div>
        {hasChildren && isOpen && node.children.map((c) => renderNode(c, depth + 1))}
      </div>
    )
  }

  return (
    <div className="flex flex-col h-full min-h-0">
      <div className="px-2 py-2 border-b border-slate-200 dark:border-slate-800 flex items-center gap-2 text-xs uppercase tracking-wide text-slate-500">
        <FolderTree className="w-3.5 h-3.5" /> Группы
      </div>
      <div className="flex-1 min-h-0 overflow-y-auto py-1">
        <div
          className={
            'flex items-center gap-1 text-sm rounded cursor-pointer pr-2 hover:bg-slate-100 dark:hover:bg-slate-800 pl-2 ' +
            (selectedId === null ? 'bg-emerald-50 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-200 font-medium' : '')
          }
          onClick={() => onSelect(null)}
        >
          <button type="button" className="flex-1 text-left py-1">Все товары</button>
        </div>
        {isLoading && <div className="px-3 py-2 text-xs text-slate-400">Загрузка…</div>}
        {!isLoading && tree.length === 0 && (
          <div className="px-3 py-2 text-xs text-slate-400">Групп ещё нет</div>
        )}
        {tree.map((n) => renderNode(n, 0))}
      </div>
    </div>
  )
}
