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="Agent fleet"
                  titleBadge={clusterStatus ? <StaleBadge status={clusterStatus} /> : undefined}
                >
                  <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>
  )
}
