import { useState } from 'react'
import type { JSX } from 'react'
import { Button, SectionCard } from '@overdeck/deck-ui'
import type { FactoryRunView } from '../../lib/factory-types'
import { useFactoryRun } from '../../lib/collector-queries'
import { FactoryDecisionPanel } from './FactoryDecisionPanel'
import { FactoryEventTable } from './FactoryEventTable'
import { FactoryPhaseTable } from './FactoryPhaseTable'
import { FactoryRunMetadata } from './FactoryRunMetadata'
import { FactoryRunSummary } from './FactoryRunSummary'
import { FactoryStopButton } from './FactoryStopButton'
import { FactoryStopHint } from './FactoryStopHint'
import { FactoryAttemptTable, FactoryDiffTable, FactoryGateTable, FactoryProcessTable } from './FactoryTraceTables'
import { FactoryTimeline } from './FactoryTimeline'
import { factoryRerunCommand, isFactoryRunning, pendingDecisions } from './factory-helpers'

export function FactoryRunCard(props: { run: FactoryRunView }): JSX.Element {
  const { run } = props
  const pending = pendingDecisions(run)
  const [expanded, setExpanded] = useState(isFactoryRunning(run.status) || pending.length > 0)
  const detailQuery = useFactoryRun(
    run.adwId,
    expanded && run.detailAvailable === true,
    isFactoryRunning(run.status),
  )
  const detailRun = detailQuery.data ?? run
  const running = isFactoryRunning(run.status)
  const rerun = factoryRerunCommand(run)
  const unavailableTables = new Set(detailRun.unavailableTables ?? [])

  return (
    <article
      data-testid="factory-run-card"
      data-adw-id={run.adwId}
      data-expanded={expanded ? 'true' : 'false'}
      className="overflow-hidden rounded-lg border border-border bg-surface"
    >
      <div
        data-testid="factory-run-header"
        className="flex min-w-0 items-start gap-2 px-4 py-3"
      >
        <Button
          variant="ghost"
          tone="neutral"
          size="md"
          onClick={() => setExpanded((value) => !value)}
          aria-expanded={expanded}
          aria-label={expanded ? 'Collapse run details' : 'Expand run details'}
          data-testid="factory-run-toggle"
          className="min-w-11 shrink-0 p-0 text-xs"
        >
          <span aria-hidden="true">{expanded ? '▾' : '▸'}</span>
        </Button>
        <div className="min-w-0 flex-1">
          <FactoryRunSummary run={run} pendingCount={pending.length} />
        </div>
        {running ? (
          <div className="shrink-0 self-start">
            <FactoryStopButton adwId={run.adwId} />
          </div>
        ) : null}
      </div>
      <div className="border-t border-border px-4 py-2">
        <a
          href={`/factory/${encodeURIComponent(run.adwId)}`}
          className="text-xs text-accent focus-visible:outline-2 focus-visible:outline-accent"
        >
          Open transcript
        </a>
      </div>
      {expanded ? (
        <div className="flex flex-col gap-3 border-t border-border px-4 py-3">
          {detailQuery.isPending && run.detailAvailable === true ? (
            <p className="text-xs text-fg-muted">Loading run details…</p>
          ) : detailQuery.isError ? (
            <p className="text-xs text-danger">Run details are unavailable.</p>
          ) : <>
          <FactoryRunMetadata run={detailRun} />
          <FactoryTimeline run={detailRun} />
          <FactoryDecisionPanel decisions={detailRun.decisions ?? []} />
          <SectionCard title="Phases">
            {detailRun.phases.length > 0 ? (
              <FactoryPhaseTable phases={detailRun.phases} attempts={detailRun.attempts ?? []} />
            ) : <p className="text-xs text-fg-muted">No phases recorded for this run.</p>}
          </SectionCard>
          <SectionCard title="Agent attempts">
            {unavailableTables.has('agent_attempts') ? (
              <p className="text-xs text-fg-muted">Not recorded by this run&apos;s factory version.</p>
            ) : (detailRun.attempts?.length ?? 0) > 0 ? (
              <FactoryAttemptTable attempts={detailRun.attempts ?? []} runAttempts={detailRun.attempts ?? []} />
            ) : <p className="text-xs text-fg-muted">No agent attempts recorded.</p>}
          </SectionCard>
          <SectionCard title="Gates">
            {unavailableTables.has('gate_results') ? (
              <p className="text-xs text-fg-muted">Not recorded by this run&apos;s factory version.</p>
            ) : (detailRun.gates?.length ?? 0) > 0 ? (
              <FactoryGateTable gates={detailRun.gates ?? []} />
            ) : <p className="text-xs text-fg-muted">No gates recorded.</p>}
          </SectionCard>
          <SectionCard title="Diffs">
            {unavailableTables.has('phase_diffs') ? (
              <p className="text-xs text-fg-muted">Not recorded by this run&apos;s factory version.</p>
            ) : (detailRun.diffs?.length ?? 0) > 0 ? (
              <FactoryDiffTable diffs={detailRun.diffs ?? []} />
            ) : <p className="text-xs text-fg-muted">No diffs recorded.</p>}
          </SectionCard>
          <SectionCard title="Processes">
            {unavailableTables.has('processes') ? (
              <p className="text-xs text-fg-muted">Not recorded by this run&apos;s factory version.</p>
            ) : (detailRun.processes?.length ?? 0) > 0 ? (
              <FactoryProcessTable processes={detailRun.processes ?? []} />
            ) : <p className="text-xs text-fg-muted">No processes recorded.</p>}
          </SectionCard>
          <SectionCard title="Events">
            {detailRun.events.length > 0 ? (
              <FactoryEventTable events={detailRun.events} runStartedAt={detailRun.startedAt} phases={detailRun.phases} />
            ) : <p className="text-xs text-fg-muted">No events recorded for this run.</p>}
          </SectionCard>
          {running ? (
            <FactoryStopHint adwId={run.adwId} />
          ) : rerun ? (
            <p className="border-t border-border pt-3 text-xs text-fg-muted" data-testid="factory-rerun-hint">
              <span className="font-semibold text-fg-subtle">Changed your mind? Start it again:</span>{' '}
              <code className="select-all rounded border border-border bg-surface-raised px-1.5 py-0.5 font-mono text-[11px] text-fg">
                {rerun}
              </code>
            </p>
          ) : null}
          </>}
        </div>
      ) : null}
    </article>
  )
}
