import { KvPanel, LimitMeter, SectionCard, StaleBadge } from '@overdeck/deck-ui'
import { adapterIdForPanel } from '../../lib/collector-client'
import { spendTodayTotal } from '../../lib/page-mappers'
import type { SystrayPanelData } from '../../lib/panel-data'
import { useCollectorState } from '../../lib/collector-queries'
import { CollectorQueryBoundary } from '../shared/CollectorQueryBoundary'

export function LimitsContent() {
  const stateQuery = useCollectorState()
  return (
    <CollectorQueryBoundary query={stateQuery}>
      {(state) => {
        const limitsPanel = state.panels.find((panel) => panel.id === 'limits')
        const limitsData = limitsPanel?.data as SystrayPanelData | undefined
        const status = state.adapters.find((adapter) => adapter.id === adapterIdForPanel('limits'))
        const spendTotal = limitsData ? spendTodayTotal(limitsData.accounts) : null

        if (!limitsData) return <div className="text-fg-muted">No limits panel in collector state.</div>

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