import { StatusChip } from '@overdeck/deck-ui'
import { useState } from 'react'
import type { JSX } from 'react'
import type { Item } from '../../lib/collector-types'

/** Halted runs are information, not questions — nothing to answer here. They get a
 * compact section of their own so they never inflate the "waiting" decision count. */
export function HaltedRunsSection(props: { items: Item[] }): JSX.Element | null {
  const { items } = props
  const [expanded, setExpanded] = useState<Record<string, boolean>>({})
  if (items.length === 0) return null

  return (
    <section className="mt-4" data-testid="halted-runs-section">
      <div className="flex items-center gap-3 border-b border-border py-3">
        <h2 className="text-[15px] font-semibold text-fg">Halted runs</h2>
        <span className="text-[12px] text-fg-subtle">
          {items.length} stopped with an error — restart or investigate; there is nothing to answer
        </span>
      </div>
      {items.map((item) => {
        const isOpen = expanded[item.id] ?? false
        return (
          <article key={item.id} className="border-b border-border" data-testid="halted-run-row">
            <button
              type="button"
              onClick={() => setExpanded((current) => ({ ...current, [item.id]: !current[item.id] }))}
              aria-expanded={isOpen}
              className="flex w-full cursor-pointer items-center gap-2 py-2.5 text-left"
            >
              <span aria-hidden="true" className="text-xs text-fg-subtle">{isOpen ? '▾' : '▸'}</span>
              <StatusChip status="failed" />
              {item.project ? <span className="text-[12px] text-fg-muted">{item.project}</span> : null}
              <span className="min-w-0 truncate text-[13px] text-fg">{item.title}</span>
            </button>
            {isOpen ? (
              <div className="pb-3 pl-6">
                <p className="whitespace-pre-wrap text-[12px] text-fg-muted">{item.detail || 'No further detail recorded.'}</p>
                {item.decision?.context ? (
                  <pre className="mt-2 overflow-x-auto rounded-md border border-border bg-surface-raised p-2 text-[11px] text-fg-muted">
                    {item.decision.context}
                  </pre>
                ) : null}
              </div>
            ) : null}
          </article>
        )
      })}
    </section>
  )
}
