import { MapCanvas } from '@overdeck/deck-ui'
import { useMemo, useState } from 'react'
import type { Item, StateResponse } from '../../lib/collector-types'
import { deriveMapGraph } from '../../lib/page-mappers'
import { useCollectorItems, useCollectorState } from '../../lib/collector-queries'
import { CollectorQueryBoundary } from '../shared/CollectorQueryBoundary'

function MapContentBody({ state, items }: { state: StateResponse; items: Item[] }) {
  const [selectedNodeId, setSelectedNodeId] = useState<string | undefined>()
  const graph = useMemo(() => deriveMapGraph(state.panels, items), [state.panels, items])
  const selected = selectedNodeId ?? graph.nodes[0]?.id

  if (graph.nodes.length === 0) {
    return <div className="text-fg-muted">No infrastructure nodes in collector state.</div>
  }

  return (
    <MapCanvas
      nodes={graph.nodes}
      edges={graph.edges}
      selectedNodeId={selected}
      onSelectNode={setSelectedNodeId}
    />
  )
}

export function MapContent() {
  const stateQuery = useCollectorState()
  const itemsQuery = useCollectorItems()
  return (
    <CollectorQueryBoundary query={stateQuery}>
      {(state) => (
        <CollectorQueryBoundary query={itemsQuery}>
          {(itemsResponse) => <MapContentBody state={state} items={itemsResponse.items} />}
        </CollectorQueryBoundary>
      )}
    </CollectorQueryBoundary>
  )
}
