import { InboxItem, KvPanel, SectionCard, StaleBadge } from '@overdeck/deck-ui'
import { inboxItemPropsFor } from '../../lib/overview-mappers'
import { agentsKvRows, clusterKvRows } from '../../lib/page-mappers'
import type { AgentsPanelData, ClusterPanelData } from '../../lib/panel-data'
import { useCollectorItems, useCollectorState } from '../../lib/collector-queries'
import { CollectorQueryBoundary } from '../shared/CollectorQueryBoundary'

export function AgentsContent() {
  const stateQuery = useCollectorState()
  const itemsQuery = useCollectorItems()
  return (
    <CollectorQueryBoundary query={stateQuery}>
      {(state) => (
        <CollectorQueryBoundary query={itemsQuery}>
          {(itemsResponse) => {
            const agentsPanel = state.panels.find((panel) => panel.id === 'agents')
            const clusterPanel = state.panels.find((panel) => panel.id === 'cluster')
            const agentsData = agentsPanel?.data as AgentsPanelData | undefined
            const clusterData = clusterPanel?.data as ClusterPanelData | undefined
            const clusterStatus = state.adapters.find((adapter) => adapter.id === 'cluster')
            const orphanItems = itemsResponse.items.filter(
              (item) => item.source === 'agent-guard' || item.id === 'orphan-agent',
            )

            if (!agentsData) {
              return <div className="text-fg-muted">No agents panel in collector state.</div>
            }

            return (
              <div className="grid grid-cols-2 gap-3.5">
                <SectionCard
                  title="Current agent processes"
                  titleBadge={clusterStatus ? <StaleBadge status={clusterStatus} /> : undefined}
                >
                  <p className="mb-2 text-xs text-fg-subtle">
                    Operating-system processes observed on the collector host at {agentsPanel?.ts ?? 'an unavailable timestamp'}. Each process is counted once by its detected runtime class. The public response publishes class totals, not raw process identities. This snapshot differs from terminal sessions and historical ledger records.
                  </p>
                  <KvPanel rows={agentsKvRows(agentsData)} />
                </SectionCard>
                {clusterData ? (
                  <SectionCard title="Cluster">
                    <KvPanel rows={clusterKvRows(clusterData)} />
                  </SectionCard>
                ) : null}
                {orphanItems.length > 0 ? (
                  <SectionCard title="Orphan candidates" className="col-span-2">
                    {orphanItems.map((item, index) => (
                      <InboxItem key={item.id} {...inboxItemPropsFor(item, index === orphanItems.length - 1)} />
                    ))}
                  </SectionCard>
                ) : null}
              </div>
            )
          }}
        </CollectorQueryBoundary>
      )}
    </CollectorQueryBoundary>
  )
}
