import type { TreeStructure } from '@/types'
import { cn } from '@/lib/utils'

interface SharedSessionTreePreviewProps {
  treeStructure: TreeStructure
  pathTaken: string[]
}

const nodeTypeColors: Record<string, string> = {
  root: 'bg-foreground',
  decision: 'bg-blue-400',
  action: 'bg-yellow-400',
  solution: 'bg-emerald-400',
  information: 'bg-muted-foreground',
}

function getNodeTitle(node: Record<string, unknown>): string {
  return (
    (node.question as string) ||
    (node.title as string) ||
    (node.node_type as string) ||
    'Untitled'
  )
}

function TreeNode({
  node,
  depth,
  pathTaken,
}: {
  node: Record<string, unknown>
  depth: number
  pathTaken: string[]
}) {
  const nodeId = (node.id as string) || ''
  const nodeType = (node.node_type as string) || 'decision'
  const isInPath = pathTaken.includes(nodeId)
  const children = (node.children as Record<string, unknown>[]) || []
  const colorClass = nodeTypeColors[nodeType] || 'bg-muted-foreground'

  return (
    <>
      <div
        className={cn(
          'flex items-center gap-2 px-3 py-1.5 text-sm',
          isInPath
            ? 'rounded-md border-l-2 border-muted-foreground bg-accent font-medium text-foreground'
            : 'text-muted-foreground'
        )}
        style={{ paddingLeft: `${depth * 16 + 12}px` }}
      >
        <span
          className={cn('h-2 w-2 shrink-0 rounded-full', colorClass)}
        />
        <span className="truncate">{getNodeTitle(node)}</span>
      </div>
      {children.map((child, index) => (
        <TreeNode
          key={(child.id as string) || index}
          node={child}
          depth={depth + 1}
          pathTaken={pathTaken}
        />
      ))}
    </>
  )
}

export function SharedSessionTreePreview({
  treeStructure,
  pathTaken,
}: SharedSessionTreePreviewProps) {
  if (!treeStructure) {
    return null
  }

  return (
    <div className="bg-card border border-border rounded-2xl">
      <div className="sticky top-0 z-10 rounded-t-2xl border-b border-border bg-black/80 px-6 py-4 backdrop-blur">
        <h3 className="text-sm font-semibold text-foreground">Tree Structure</h3>
      </div>
      <div className="max-h-[600px] overflow-y-auto py-2">
        <TreeNode node={treeStructure as unknown as Record<string, unknown>} depth={0} pathTaken={pathTaken} />
      </div>
    </div>
  )
}

export default SharedSessionTreePreview
