import { useState } from 'react'
import { ChevronRight, ChevronDown, Pencil, Trash2, Plus, MoveVertical, AlertTriangle } from 'lucide-react'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible'
import type { RubroTreeNode, Rubro } from '../types'

const MAX_DEPTH = 10

export interface CategoryTreeNodeProps {
  node: RubroTreeNode
  depth: number
  onEdit: (rubro: Rubro) => void
  onDelete: (rubro: Rubro) => void
  onAddChild: (parentId: number) => void
  onMove: (rubro: Rubro) => void
  canEdit: boolean
}

export function CategoryTreeNode({
  node,
  depth,
  onEdit,
  onDelete,
  onAddChild,
  onMove,
  canEdit,
}: CategoryTreeNodeProps) {
  const [open, setOpen] = useState(false)

  // Depth guard: prevents infinite recursion on malformed data
  if (depth > MAX_DEPTH) {
    return (
      <div className="flex items-center gap-2 py-1 px-2 text-xs text-muted-foreground" role="alert">
        <AlertTriangle className="h-3 w-3 text-warning shrink-0" />
        <span>Profundidad máxima alcanzada ({MAX_DEPTH} niveles)</span>
      </div>
    )
  }

  const hasChildren = node.hijos.length > 0

  // Coerce to Rubro for callbacks (tree node has compatible shape minus fechas)
  const asRubro: Rubro = {
    id: node.id,
    nombre: node.nombre,
    orden: node.orden,
    activo: node.activo,
    parentId: node.parentId,
    tarifarioBaseId: node.tarifarioBaseId,
    fechaCreacion: '',
    fechaModificacion: null,
  }

  const indentStyle = { paddingLeft: `${depth * 16}px` }

  const nodeContent = (
    <div
      className={cn(
        'group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-accent',
        !node.activo && 'opacity-60',
      )}
      style={indentStyle}
    >
      {/* Expand/collapse toggle */}
      {hasChildren ? (
        <CollapsibleTrigger asChild>
          <button
            type="button"
            aria-label={open ? `Colapsar ${node.nombre}` : `Expandir ${node.nombre}`}
            className="flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground"
          >
            {open ? (
              <ChevronDown className="h-3.5 w-3.5" />
            ) : (
              <ChevronRight className="h-3.5 w-3.5" />
            )}
          </button>
        </CollapsibleTrigger>
      ) : (
        <span className="h-5 w-5 shrink-0" aria-hidden="true" />
      )}

      {/* Node name */}
      <span className={cn('flex-1 truncate font-medium', !node.activo && 'text-muted-foreground')}>
        {node.nombre}
      </span>

      {/* Inactive badge */}
      {!node.activo && (
        <Badge variant="secondary" className="text-[10px] px-1.5 py-0 shrink-0">
          inactivo
        </Badge>
      )}

      {/* Action buttons — only if canEdit */}
      {canEdit && (
        <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
          {/* CAT-002: disabled when leaf-with-avisos; PRD-002 activates the real data path */}
          <Button
            variant="ghost"
            size="sm"
            className="h-6 w-6 p-0"
            aria-label={`Agregar subrubro en ${node.nombre}`}
            disabled={node.tieneAvisos === true}
            title={node.tieneAvisos === true ? 'El rubro contiene avisos asignados. Muévalos antes de agregar sub-rubros.' : undefined}
            onClick={() => onAddChild(node.id)}
          >
            <Plus className="h-3.5 w-3.5" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            className="h-6 w-6 p-0"
            aria-label={`Editar ${node.nombre}`}
            onClick={() => onEdit(asRubro)}
          >
            <Pencil className="h-3.5 w-3.5" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            className="h-6 w-6 p-0"
            aria-label={`Mover ${node.nombre}`}
            onClick={() => onMove(asRubro)}
          >
            <MoveVertical className="h-3.5 w-3.5" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            className="h-6 w-6 p-0 text-destructive hover:text-destructive"
            aria-label={`Eliminar ${node.nombre}`}
            onClick={() => onDelete(asRubro)}
          >
            <Trash2 className="h-3.5 w-3.5" />
          </Button>
        </div>
      )}
    </div>
  )

  if (!hasChildren) {
    return <div>{nodeContent}</div>
  }

  return (
    <Collapsible open={open} onOpenChange={setOpen}>
      {nodeContent}
      <CollapsibleContent>
        {node.hijos.map((child) => (
          <CategoryTreeNode
            key={child.id}
            node={child}
            depth={depth + 1}
            onEdit={onEdit}
            onDelete={onDelete}
            onAddChild={onAddChild}
            onMove={onMove}
            canEdit={canEdit}
          />
        ))}
      </CollapsibleContent>
    </Collapsible>
  )
}
