import { useLayoutEffect, useRef, useState, useCallback } from 'react'
import { IconPlus } from '@tabler/icons-react'
import RoadmapNodeCard from './RoadmapNodeCard'
import { NODE_KIND } from '../../lib/roadmaps'

const COLUMN_WIDTH = 230
const COLUMN_GAP = 48

/**
 * Steckbrett: Spalten von links (Start) nach rechts (Ziele), Knoten vertikal
 * gestapelt, Kanten als SVG-Overlay. Verbinden per Klick-Modus:
 * Connect-Handle am Quellknoten -> gueltige Ziele (Spalte weiter rechts) anklicken.
 */
export default function RoadmapBoard({
  roadmap,
  nodes,
  selectedNode,
  readOnly,
  onSelectNode,
  onAddNode,
  onConnect,
}) {
  const containerRef = useRef(null)
  const nodeRefs = useRef({})
  const [edges, setEdges] = useState([])
  const [connectSource, setConnectSource] = useState(null)

  const columnCount = Math.max(roadmap.columnCount || 3, 2)
  const columns = Array.from({ length: columnCount }, (_, c) =>
    nodes.filter((n) => n.column === c).sort((a, b) => (a.row || 0) - (b.row || 0))
  )

  const setNodeRef = useCallback((id) => (el) => {
    if (el) nodeRefs.current[id] = el
    else delete nodeRefs.current[id]
  }, [])

  // Kanten-Geometrie nach jedem Layout neu berechnen (Anker relativ zum Board)
  useLayoutEffect(() => {
    const container = containerRef.current
    if (!container) return
    const compute = () => {
      const base = container.getBoundingClientRect()
      const next = []
      for (const node of nodes) {
        for (const sourceId of node.sourceIds || []) {
          const sourceEl = nodeRefs.current[sourceId]
          const targetEl = nodeRefs.current[node.$id]
          if (!sourceEl || !targetEl) continue
          const s = sourceEl.getBoundingClientRect()
          const t = targetEl.getBoundingClientRect()
          next.push({
            id: `${sourceId}-${node.$id}`,
            x1: s.right - base.left,
            y1: s.top + s.height / 2 - base.top,
            x2: t.left - base.left,
            y2: t.top + t.height / 2 - base.top,
          })
        }
      }
      setEdges(next)
    }
    compute()
    const observer = new ResizeObserver(compute)
    observer.observe(container)
    return () => observer.disconnect()
  }, [nodes, columnCount])

  const handleStartConnect = (node) => setConnectSource(node)

  const handleSelect = async (node) => {
    if (connectSource) {
      if (node.column > connectSource.column) {
        await onConnect(connectSource, node)
      }
      setConnectSource(null)
      return
    }
    onSelectNode(node)
  }

  const columnLabel = (c) => {
    if (c === 0) return 'Start'
    if (c === columnCount - 1) return 'Ziele'
    return `Phase ${c}`
  }

  return (
    <div style={{ overflowX: 'auto', paddingBottom: 8 }}>
      {connectSource && (
        <div
          className="muted"
          style={{ fontSize: 13, marginBottom: 8, display: 'flex', alignItems: 'center', gap: 10 }}
        >
          Verbinden von <strong>{connectSource.title}</strong>: Zielknoten rechts davon anklicken.
          <button type="button" className="ui-btn" onClick={() => setConnectSource(null)}>Abbrechen</button>
        </div>
      )}
      <div
        ref={containerRef}
        style={{
          position: 'relative',
          display: 'grid',
          gridTemplateColumns: `repeat(${columnCount}, ${COLUMN_WIDTH}px)`,
          gap: `16px ${COLUMN_GAP}px`,
          alignItems: 'start',
          minWidth: columnCount * (COLUMN_WIDTH + COLUMN_GAP),
          padding: '8px 4px',
        }}
      >
        <svg
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none', zIndex: 0 }}
        >
          <defs>
            <marker id="roadmap-arrow" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto">
              <path d="M0,0 L8,4 L0,8 Z" fill="var(--text-muted, #94a3b8)" />
            </marker>
          </defs>
          {edges.map((e) => {
            const dx = Math.max((e.x2 - e.x1) / 2, 24)
            return (
              <path
                key={e.id}
                d={`M ${e.x1} ${e.y1} C ${e.x1 + dx} ${e.y1}, ${e.x2 - dx} ${e.y2}, ${e.x2} ${e.y2}`}
                fill="none"
                stroke="var(--text-muted, #94a3b8)"
                strokeWidth="1.5"
                markerEnd="url(#roadmap-arrow)"
                opacity="0.7"
              />
            )
          })}
        </svg>

        {columns.map((columnNodes, c) => (
          <div key={c} style={{ display: 'flex', flexDirection: 'column', gap: 14, zIndex: 1 }}>
            <div className="faint" style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5 }}>
              {columnLabel(c)}
            </div>
            {columnNodes.map((node) => (
              <RoadmapNodeCard
                key={node.$id}
                node={node}
                selected={selectedNode?.$id === node.$id}
                readOnly={readOnly}
                connectSource={connectSource}
                isValidTarget={Boolean(connectSource) && node.column > connectSource.column}
                onSelect={handleSelect}
                onStartConnect={handleStartConnect}
                nodeRef={setNodeRef(node.$id)}
              />
            ))}
            {!readOnly && c > 0 && (
              <button
                type="button"
                className="ui-btn"
                style={{ borderStyle: 'dashed', fontSize: 12 }}
                onClick={() => onAddNode(c, c === columnCount - 1 ? NODE_KIND.GOAL : NODE_KIND.STEP, columnNodes.length)}
              >
                <IconPlus size={14} /> {c === columnCount - 1 ? 'Ziel' : 'Schritt'}
              </button>
            )}
          </div>
        ))}
      </div>
    </div>
  )
}
