import { DeckTooltipLayer, SectionCard, StaleBadge } from '@overdeck/deck-ui'
import type { JSX } from 'react'
import { adapterIdForPanel } from '../../lib/collector-client'
import type { AdapterStatus } from '../../lib/collector-types'
import type { FactoryPanelData } from '../../lib/factory-types'
import { useCollectorState } from '../../lib/collector-queries'
import { CollectorQueryBoundary } from '../shared/CollectorQueryBoundary'
import { FactoryRunCard } from './FactoryRunCard'
import { sortFactoryRuns } from './factory-helpers'

function adapterUnavailable(adapter: AdapterStatus | undefined, panelMissing: boolean): boolean {
  if (panelMissing) return true
  if (!adapter) return true
  return adapter.consecutiveErrors > 0 || Boolean(adapter.lastError)
}

function FactoryUnavailableState(props: {
  adapter: AdapterStatus | undefined
  panelMissing: boolean
  data: FactoryPanelData | undefined
}): JSX.Element {
  if (props.panelMissing) {
    return (
      <p className="text-sm text-fg-muted">
        Factory panel is not present in collector state. Check that the factory adapter is enabled.
      </p>
    )
  }

  if (props.adapter?.lastError || (props.adapter?.consecutiveErrors ?? 0) > 0) {
    return (
      <p className="text-sm text-danger">
        Factory collector is failing
        {props.adapter?.lastError ? `: ${props.adapter.lastError}` : '.'}
      </p>
    )
  }

  if (props.data && !props.data.dbPresent) {
    return (
      <p className="text-sm text-fg-muted">
        Factory trace database is not available
        {props.data.dbPath ? ` at ${props.data.dbPath}` : ''}.
      </p>
    )
  }

  return <p className="text-sm text-fg-muted">Factory collector is unavailable.</p>
}

function FactoryEmptyState(): JSX.Element {
  return (
    <p className="text-sm text-fg-muted">
      No factory runs recorded yet. Completed and live runs will appear here once sessions land in the global trace database.
    </p>
  )
}

export function FactoryContent(): JSX.Element {
  const stateQuery = useCollectorState()

  return (
    <CollectorQueryBoundary query={stateQuery}>
      {(state) => {
        const panel = state.panels.find((entry) => entry.id === 'factory-runs')
        const data = panel?.data as FactoryPanelData | undefined
        const adapter = state.adapters.find((entry) => entry.id === adapterIdForPanel('factory-runs'))
        const panelMissing = !panel
        const adapterFailed = adapterUnavailable(adapter, panelMissing)
        const dbMissing = data?.dbPresent === false
        const runs = sortFactoryRuns(data?.runs ?? [])

        return (
          <>
            <SectionCard
              title="Factory runs"
              titleBadge={adapter ? <StaleBadge status={adapter} /> : undefined}
              className="flex min-h-0 flex-col"
            >
              {adapterFailed ? (
                <FactoryUnavailableState adapter={adapter} panelMissing={panelMissing} data={data} />
              ) : dbMissing ? (
                <FactoryUnavailableState adapter={adapter} panelMissing={false} data={data} />
              ) : runs.length === 0 ? (
                <FactoryEmptyState />
              ) : (
                <div className="flex flex-col gap-3" data-testid="factory-run-list">
                  {runs.map((run) => (
                    <FactoryRunCard key={run.adwId} run={run} />
                  ))}
                </div>
              )}
            </SectionCard>
            <DeckTooltipLayer />
          </>
        )
      }}
    </CollectorQueryBoundary>
  )
}
