import { useState, useMemo, useCallback } from 'react'
import { TreePreviewNode } from '@/components/tree-preview/TreePreviewNode'
import type { SharedLinksMap } from '@/components/tree-preview/TreePreviewPanel'
import type { TreeStructure } from '@/types'

interface StaticTreePreviewProps {
  tree: TreeStructure
  name?: string
}

function findNodeInTree(nodeId: string, tree: TreeStructure): TreeStructure | null {
  if (tree.id === nodeId) return tree
  if (tree.children) {
    for (const child of tree.children) {
      const found = findNodeInTree(nodeId, child)
      if (found) return found
    }
  }
  return null
}

function buildSharedLinksMap(node: TreeStructure, map: SharedLinksMap = new Map()): SharedLinksMap {
  const nodeLabel = node.type === 'decision' ? node.question : node.title
  if (node.type === 'decision' && node.options) {
    for (const opt of node.options) {
      if (opt.next_node_id) {
        const existing = map.get(opt.next_node_id) || []
        existing.push({ id: node.id, label: nodeLabel || 'Untitled' })
        map.set(opt.next_node_id, existing)
      }
    }
  }
  if (node.type === 'action' && node.next_node_id) {
    const existing = map.get(node.next_node_id) || []
    existing.push({ id: node.id, label: nodeLabel || 'Untitled' })
    map.set(node.next_node_id, existing)
  }
  if (node.children) {
    for (const child of node.children) {
      buildSharedLinksMap(child, map)
    }
  }
  return map
}

export function StaticTreePreview({ tree, name }: StaticTreePreviewProps) {
  const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null)

  const findNode = useCallback(
    (nodeId: string) => findNodeInTree(nodeId, tree),
    [tree]
  )

  const sharedLinksMap = useMemo(() => buildSharedLinksMap(tree), [tree])

  return (
    <div className="flex h-full flex-col">
      <div className="border-b border-border px-4 py-2">
        <h3 className="text-sm font-semibold text-foreground">
          Preview: {name || 'Untitled Flow'}
        </h3>
        <p className="text-xs text-muted-foreground">
          Click a node to select
        </p>
      </div>
      <div className="flex-1 overflow-auto p-4">
        <div className="inline-block min-w-full">
          <TreePreviewNode
            node={tree}
            selectedNodeId={selectedNodeId}
            onSelect={setSelectedNodeId}
            depth={0}
            findNode={findNode}
            sharedLinksMap={sharedLinksMap}
          />
        </div>
      </div>
    </div>
  )
}
