import { KvPanel, SectionCard, StaleBadge } from '@overdeck/deck-ui'
import { useState } from 'react'
import { adapterIdForPanel } from '../../lib/collector-client'
import type { AdapterStatus, Panel } from '../../lib/collector-types'
import { planKvRows } from '../../lib/overview-mappers'
import type { HarnessPlansPanelData } from '../../lib/panel-data'
import { OVERVIEW_KV_SCROLL_CLASS } from './overview-layout'

export const PLANS_OVERVIEW_PREVIEW_LIMIT = 15

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

export function PlansCard({ panels, adapters }: PlansCardProps) {
  const [expanded, setExpanded] = useState(false)
  const panel = panels.find((p) => p.id === 'plans')
  const rows = panel ? planKvRows(panel.data as HarnessPlansPanelData) : []
  const hasMore = rows.length > PLANS_OVERVIEW_PREVIEW_LIMIT
  const visibleRows = expanded || !hasMore ? rows : rows.slice(0, PLANS_OVERVIEW_PREVIEW_LIMIT)
  const status = adapters.find((a) => a.id === adapterIdForPanel('plans'))

  const action = hasMore
    ? {
        label: expanded ? 'show less ↑' : `+${rows.length - PLANS_OVERVIEW_PREVIEW_LIMIT} more →`,
        onClick: () => setExpanded((value) => !value),
      }
    : { label: 'plans →', href: '/plans' }

  return (
    <SectionCard title="Plans" titleBadge={status ? <StaleBadge status={status} /> : undefined} action={action}>
      {rows.length === 0 ? (
        <p className="text-[12px] text-fg-muted">
          {panel ? 'No plan runs in the latest snapshot.' : 'Plans unavailable — harness adapter has not returned data yet.'}
        </p>
      ) : (
        <div className={OVERVIEW_KV_SCROLL_CLASS}>
          <KvPanel rows={visibleRows} />
        </div>
      )}
    </SectionCard>
  )
}
