import { KvPanel, LimitMeter, SectionCard, StaleBadge } from '@overdeck/deck-ui'
import { adapterIdForPanel } from '../../lib/collector-client'
import type { AdapterStatus, Panel } from '../../lib/collector-types'
import { spendTodayTotal } from '../../lib/overview-mappers'
import type { SystrayPanelData } from '../../lib/panel-data'
import { OVERVIEW_FILL_BODY_CLASS, OVERVIEW_FILL_CARD_CLASS } from './overview-layout'

export interface LimitsCardProps {
  panels: Panel[]
  adapters: AdapterStatus[]
}

export function LimitsCard({ panels, adapters }: LimitsCardProps) {
  const panel = panels.find((p) => p.id === 'limits')
  const accounts = panel ? (panel.data as SystrayPanelData).accounts : []
  const spend = spendTodayTotal(accounts)
  const status = adapters.find((a) => a.id === adapterIdForPanel('limits'))

  return (
    <SectionCard
      title="Limits & spend"
      titleBadge={status ? <StaleBadge status={status} /> : undefined}
      className={OVERVIEW_FILL_CARD_CLASS}
    >
      <div className={OVERVIEW_FILL_BODY_CLASS}>
        {accounts.map((account) => (
          <LimitMeter key={account.slug} account={account} />
        ))}
        <KvPanel rows={[{ label: 'spend today', value: spend === null ? '—' : `$${spend.toFixed(2)}` }]} />
      </div>
    </SectionCard>
  )
}
