import { useEffect, useRef, useState, type JSX } from 'react'
import { Card } from '@astryxdesign/core'
import { Button } from './Button'
import { AgentActivityRow, type AgentActivityItem } from './AgentActivityRow'

export type { AgentActivityItem, AgentActivityBase, AgentEditItem, AgentGroupItem } from './AgentActivityRow'
/** Legacy transport-era shape retained while callers migrate to story items. */
export interface AgentTurn { at: number; durMs: number | null; phase: string; summary: string; detail?: string; journalSeq?: number }

export function AgentFeed(props: {
  items?: AgentActivityItem[]
  turns?: AgentTurn[]
  live: boolean
  rawLogAvailable?: boolean
  events?: unknown[]
  onOpenDiagnostics?: (itemId: string | null, trigger: HTMLElement) => void
  onToggleGroup?: (itemId: string) => void
}): JSX.Element {
  const shell = useRef<HTMLDivElement>(null)
  const [expandedDiffs, setExpandedDiffs] = useState<Set<string>>(() => new Set())
  const [showRaw, setShowRaw] = useState(false)
  useEffect(() => {
    if (props.live && shell.current) shell.current.scrollTop = shell.current.scrollHeight
  }, [props.items?.length, props.turns?.length, props.live])
  const legacy = props.items === undefined
  const items = props.items ?? [...(props.turns ?? [])].sort((a, b) => a.at - b.at).map((turn, index) => ({ id: `legacy-${index}`, at: turn.at, kind: 'progress' as const, title: turn.phase, summary: `${turn.durMs === null ? 'In progress — ' : ''}${turn.summary}`, diagnosticEventIds: [] }))
  const open = props.onOpenDiagnostics ?? (() => undefined)
  const toggle = props.onToggleGroup ?? (() => undefined)
  return <Card className="flex min-h-0 flex-1 flex-col overflow-hidden">
    <header className="flex border-b border-border px-5 py-4"><div><h2 id="agent-feed-title" tabIndex={-1} className="text-base font-semibold text-fg">Agent activity</h2><p className="mt-1 text-xs text-fg-muted">{props.live ? 'Following recorded activity as it arrives.' : 'Recorded activity.'}</p></div><div className="ml-auto flex items-start gap-2"><Button variant="ghost" tone="neutral" size="sm" className="text-xs underline" onClick={(event) => open(null, event.currentTarget)}>Diagnostics</Button>{legacy && <Button variant="ghost" tone="neutral" size="sm" aria-pressed={showRaw} className="text-xs underline" onClick={() => setShowRaw(value => !value)}>{showRaw ? 'Show friendly feed' : 'Show raw log'}</Button>}</div></header>
    {!props.live && <p className="border-b border-border bg-surface-raised px-5 py-2 text-xs text-fg-muted">This agent attempt ended.</p>}
    <p className="sr-only" aria-live="polite">{items.filter(item => item.kind === 'warning' || item.kind === 'outcome').map(item => item.title).join('. ')}</p>
    <div ref={shell} data-testid="agent-feed-shell" className="min-h-0 flex-1 overflow-y-auto p-4">
      {showRaw && legacy ? <pre>{props.rawLogAvailable ? (props.events as { id: string; text: string }[] | undefined)?.map(event => `${event.id}\n${event.text}`).join('\n\n') : 'Raw event detail is not provided by this run.'}</pre> : items.length === 0 ? <p className="rounded-lg border border-dashed border-border p-5 text-center text-sm text-fg-muted">No activity has been recorded for this agent.</p> : <ol className="grid gap-3">{items.map(item => <li key={item.id}><AgentActivityRow item={item} onOpenDiagnostics={(id, trigger) => open(id, trigger)} onToggleGroup={toggle} diffExpanded={expandedDiffs.has(item.id)} onToggleDiff={() => setExpandedDiffs(old => { const next = new Set(old); next.has(item.id) ? next.delete(item.id) : next.add(item.id); return next })}/></li>)}</ol>}
    </div>
  </Card>
}