import { BotTable, KvPanel, SectionCard, StaleBadge } from '@overdeck/deck-ui'
import { adapterIdForPanel } from '../../lib/collector-client'
import type { BotsPanelData } from '../../lib/panel-data'
import { useCollectorState } from '../../lib/collector-queries'
import { CollectorQueryBoundary } from '../shared/CollectorQueryBoundary'

function summaryRows(bots: BotsPanelData['bots']) {
  const running = bots.filter((bot) => bot.runtimeStatus === 'running').length
  const live = bots.filter((bot) => bot.status === 'live').length
  const slow = bots.filter((bot) => bot.status === 'slow').length
  const idle = bots.filter((bot) => bot.status === 'idle').length
  const silent = bots.filter((bot) => bot.status === 'down' && bot.runtimeStatus === 'running').length
  const cost24h = bots.reduce((sum, bot) => sum + (bot.cost ?? 0), 0)
  const reporting = bots.filter((bot) => bot.messagesTotal > 0).length

  return [
    { label: 'Registered', value: String(bots.length) },
    { label: 'Running', value: String(running), intent: running > 0 ? 'ok' as const : undefined },
    { label: 'Live 24h', value: String(live), intent: live > 0 ? 'ok' as const : undefined },
    { label: 'Slow', value: String(slow), intent: slow > 0 ? 'warn' as const : undefined },
    { label: 'Idle', value: String(idle) },
    { label: 'Silent', value: String(silent), intent: silent > 0 ? 'err' as const : undefined },
    { label: 'Reporting', value: `${reporting}/${bots.length}` },
    { label: 'Cost 24h', value: cost24h > 0 ? `$${cost24h.toFixed(1)}` : '—' },
  ]
}

export function BotsContent() {
  const stateQuery = useCollectorState()
  return (
    <CollectorQueryBoundary query={stateQuery}>
      {(state) => {
        const botsPanel = state.panels.find((panel) => panel.id === 'bots')
        const botsData = botsPanel?.data as BotsPanelData | undefined
        const status = state.adapters.find((adapter) => adapter.id === adapterIdForPanel('bots'))

        if (!botsPanel) {
          return <div className="text-fg-muted">Bots unavailable — botmaster adapter has not returned data yet.</div>
        }

        const bots = botsData?.bots ?? []
        const reporting = bots.filter((bot) => bot.messagesTotal > 0).length
        const mirrorLag = botsData?.mirrorLagHours ?? null
        const d1Latest = botsData?.d1LatestAt ?? null

        return (
          <div className="flex flex-col gap-3.5">
            <SectionCard title="Fleet summary" titleBadge={status ? <StaleBadge status={status} /> : undefined}>
              <KvPanel rows={summaryRows(bots)} />
              <p className="mt-2 text-[11px] text-fg-muted">
                Volume from Botmaster D1 mirror (Telegram chat_messages + LLM metrics). Runtime status from registry.
                Last active = newest poll, message, or LLM call; last message = newest chat_messages row only.
                {d1Latest ? ` Newest mirrored row: ${d1Latest.replace('T', ' ').replace(/\.\d+Z$/, ' UTC')}.` : ' No mirrored rows yet.'}
                {mirrorLag !== null && mirrorLag > 24 ? (
                  <span className="text-warning"> Mirror is {mirrorLag}h stale — recent Telegram traffic may not appear until Botmaster D1 sync is fixed.</span>
                ) : null}
                {reporting < bots.length ? ` Reporting ${reporting}/${bots.length} bots.` : null}
              </p>
            </SectionCard>
            <SectionCard title="Bots (Botmaster)">
              {bots.length > 0 ? (
                <BotTable
                  bots={bots.map((bot) => ({
                    id: bot.id,
                    name: bot.name,
                    subtitle: bot.project,
                    status: bot.status,
                    statusDetail: bot.statusDetail,
                    messages24h: bot.messages24h,
                    messagesTotal: bot.messagesTotal,
                    errors: bot.errors,
                    cost: bot.cost,
                    costTotal: bot.costTotal,
                    lastActivityAt: bot.lastActivityAt,
                    lastMessageAt: bot.lastMessageAt,
                  }))}
                  density="full"
                />
              ) : (
                <p className="text-[12px] text-fg-muted">No bots in the latest snapshot.</p>
              )}
            </SectionCard>
          </div>
        )
      }}
    </CollectorQueryBoundary>
  )
}
