import {
  ArrowDownUp,
  Network,
  RefreshCw,
  ShieldCheck,
  Timer,
} from 'lucide-react'

import { SectionCards, type SectionCardItem } from '@/components/section-cards'
import { SectionCardsSkeleton } from '@/components/skeletons'
import { formatDateTime, moduleIntervalLabel } from '@/lib/modules/display'
import {
  communityLabel,
  dohProfileLabel,
  moduleDohProfileIds,
} from '@/lib/modules/helpers'
import { dohPolicyRu } from '@/lib/ui-labels'
import type { AsEntry, BgpCommunity, DohProfile, ModuleRow } from '@/types/api'

interface ModuleKpiCardsProps {
  mod: ModuleRow | null
  communities: BgpCommunity[]
  dohProfiles: DohProfile[]
  asEntries: AsEntry[]
  loading?: boolean
}

export function ModuleKpiCards({
  mod,
  communities,
  dohProfiles,
  asEntries,
  loading = false,
}: ModuleKpiCardsProps) {
  if (loading || !mod) {
    return <SectionCardsSkeleton count={5} />
  }

  const asPrefixTotal = asEntries.reduce((acc, entry) => acc + (entry.prefix_count ?? 0), 0)
  const dohIds = moduleDohProfileIds(mod)

  const items: SectionCardItem[] = [
    {
      label: 'Приоритет',
      value: String(mod.priority ?? 0),
      hint: 'порядок в сборке ревизии',
      icon: <ArrowDownUp className="size-3.5" />,
    },
    {
      label: 'Интервал',
      value: moduleIntervalLabel(mod),
      hint: 'refresh_interval_sec / cron',
      icon: <Timer className="size-3.5" />,
    },
    {
      label: 'DoH',
      value: mod.type === 'DOMAINS' ? dohPolicyRu(mod.doh_resolver_policy) : '—',
      hint:
        mod.type === 'DOMAINS'
          ? dohIds.length
            ? dohIds.map((id) => dohProfileLabel(id, dohProfiles)).join('; ')
            : 'Системный DNS'
          : 'не применимо',
      icon: <Network className="size-3.5" />,
    },
    {
      label: 'Community по умолч.',
      value: communityLabel(mod.default_community_id, communities),
      hint: 'для записей без своего community',
      icon: <ShieldCheck className="size-3.5" />,
    },
    {
      label: 'Последнее обновление',
      value: formatDateTime(mod.last_refreshed_at),
      hint:
        mod.type === 'AS_PREFIXES'
          ? `ASN: ${asEntries.length}, префиксов: ${asPrefixTotal}`
          : 'время последнего refresh',
      icon: <RefreshCw className="size-3.5" />,
    },
  ]

  return <SectionCards items={items} />
}
