import { GitBranch } from 'lucide-react'
import { BranchNode } from './BranchNode'
import type { BranchResponse } from '@/types/branching'

interface BranchTreeNode {
  branch: BranchResponse
  depth: number
  children: BranchTreeNode[]
}

function buildTree(branches: BranchResponse[]): BranchTreeNode[] {
  const map = new Map<string, BranchTreeNode>()
  const roots: BranchTreeNode[] = []

  for (const branch of branches) {
    map.set(branch.id, { branch, depth: 0, children: [] })
  }

  for (const branch of branches) {
    const node = map.get(branch.id)!
    if (branch.parent_branch_id && map.has(branch.parent_branch_id)) {
      const parent = map.get(branch.parent_branch_id)!
      node.depth = parent.depth + 1
      parent.children.push(node)
    } else {
      roots.push(node)
    }
  }

  return roots
}

function flattenTree(nodes: BranchTreeNode[]): Array<{ branch: BranchResponse; depth: number }> {
  const result: Array<{ branch: BranchResponse; depth: number }> = []
  for (const node of nodes) {
    result.push({ branch: node.branch, depth: node.depth })
    if (node.children.length > 0) {
      result.push(...flattenTree(node.children))
    }
  }
  return result
}

interface BranchMapProps {
  branches: BranchResponse[]
  activeBranchId: string | null
  onSelectBranch: (branchId: string) => void
}

export function BranchMap({ branches, activeBranchId, onSelectBranch }: BranchMapProps) {
  const roots = buildTree(branches)
  const flat = flattenTree(roots)

  return (
    <div className="flex flex-col gap-2">
      <div className="flex items-center gap-1.5 px-2 pb-1">
        <GitBranch size={14} className="text-accent-text" />
        <span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
          Branch Map
        </span>
        <span className="ml-auto text-[10px] font-medium text-muted-foreground">{branches.length}</span>
      </div>

      {flat.length === 0 ? (
        <p className="px-2 text-xs text-muted-foreground">No branches yet.</p>
      ) : (
        <div className="flex flex-col gap-1.5">
          {flat.map(({ branch, depth }) => (
            <BranchNode
              key={branch.id}
              branch={branch}
              depth={depth}
              isActive={branch.id === activeBranchId}
              onClick={onSelectBranch}
            />
          ))}
        </div>
      )}
    </div>
  )
}
