import { AnalyticsCardShell } from '@/components/analytics/analytics-card-shell'
import { AnalyticsKpiRow } from '@/components/analytics/analytics-kpi-row'
import { ChartDonutMetric } from '@/components/analytics/chart-donut-metric'
import { peerSessionBreakdown } from '@/lib/metrics'
import { aggregateNetworkMetrics } from '@/queries/overview'
import type { PeerRow, SpeakerRow } from '@/types/api'

export function NetworkOverviewAnalyticsCard({
  peers,
  speakers,
  loading,
}: {
  peers: PeerRow[]
  speakers: SpeakerRow[]
  loading?: boolean
}) {
  const net = aggregateNetworkMetrics(peers, speakers)
  const slices = peerSessionBreakdown(peers)
  const total = slices.reduce((sum, slice) => sum + slice.count, 0)

  return (
    <AnalyticsCardShell
      title="Сводка BGP"
      description="Established, online и mismatch по live-данным"
      info="Снимок текущего состояния пиров и спикеров."
    >
      <AnalyticsKpiRow
        items={[
          {
            label: 'Пиры Established',
            value: loading ? '—' : `${net.peersEstablished}/${net.peersEnabled}`,
            delta: {
              direction: net.peersMismatch > 0 ? 'down' : 'up',
              label: net.peersMismatch > 0 ? `${net.peersMismatch} mismatch` : 'сессии в норме',
              tone: net.peersMismatch > 0 ? 'warning' : 'success',
            },
          },
          {
            label: 'Спикеры online',
            value: loading ? '—' : `${net.speakersOnline}/${net.speakersTotal}`,
            delta: {
              direction: net.speakersOnline < net.speakersTotal ? 'down' : 'up',
              label:
                net.speakersOnline < net.speakersTotal
                  ? `${net.speakersTotal - net.speakersOnline} offline`
                  : 'все online',
              tone: net.speakersOnline < net.speakersTotal ? 'warning' : 'success',
            },
          },
          {
            label: 'Пиры всего',
            value: loading ? '—' : String(net.peersTotal),
            delta: { direction: 'neutral', label: 'в каталоге', tone: 'muted' },
          },
        ]}
      />
      {loading ? (
        <div className="flex h-48 items-center justify-center text-sm text-muted-foreground">
          Загрузка…
        </div>
      ) : (
        <ChartDonutMetric slices={slices} centerLabel="Пиры" centerValue={total} />
      )}
    </AnalyticsCardShell>
  )
}
