import { KpiTile, PhaseBars, RunLanes, SectionCard, SectionHeading, StaleBadge } from '@overdeck/deck-ui'
import { adapterIdForPanel } from '../../lib/collector-client'
import type { AdapterStatus, Panel } from '../../lib/collector-types'
import { forensicsTitleFor, pickForensicsPanel, runIdFromForensicsPanelId } from '../../lib/overview-mappers'
import type { ForensicsPanelData } from '../../lib/panel-data'

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

/** KPI tile grid + attribution + runs, for the most recent forensics:<runId> panel. */
export function ForensicsSection({ panels, adapters }: ForensicsSectionProps) {
  const panel = pickForensicsPanel(panels)
  if (!panel) return null

  const data = panel.data as ForensicsPanelData
  const runId = runIdFromForensicsPanelId(panel.id)
  const title = forensicsTitleFor(runId, panels.find((p) => p.id === 'plans'))
  const status = adapters.find((a) => a.id === adapterIdForPanel(panel.id))

  return (
    <div className="flex flex-col gap-3">
      <SectionHeading
        title={`Run forensics — ${title}`}
        subtitle="· last factory run"
        titleBadge={status ? <StaleBadge status={status} /> : undefined}
        action={{ label: 'all runs →', href: '/plans' }}
      />
      <div className="grid grid-cols-6 gap-3">
        {data.tiles.map((tile) => (
          <KpiTile key={tile.key} tile={tile} />
        ))}
      </div>
      <div className="grid grid-cols-2 gap-3">
        <SectionCard title="Where the time went">
          <PhaseBars attribution={data.attribution} />
        </SectionCard>
        <SectionCard title="Runs" action={{ label: 'full timeline →' }}>
          <RunLanes runs={data.runs} segments={data.segments} />
        </SectionCard>
      </div>
    </div>
  )
}
