import React from 'react'
import type { FleetHost, HostState, OffloadAction, OffloadControlModel } from './offload-types'
import { CapabilityProbeList } from './CapabilityProbeList'

export interface OffloadControlProps {
  control: OffloadControlModel
  selectedHost: FleetHost | null
  onAction: (action: OffloadAction) => void
  pendingVerb: string | null
  actionError: { verb: string; message: string } | null
}

const FSM_STATES: HostState[] = ['available', 'draining', 'maintenance', 'restoring', 'degraded']

const SUPPORTED_OFFLOAD_VERBS = new Set([
  'box-drain',
  'box-restore',
  'host-quarantine',
  'host-unquarantine',
  'admission-reconcile',
  'ci-reconcile',
  'recall-spill',
])

const HOST_SCOPED_VERBS = new Set([
  'box-drain',
  'box-restore',
  'host-quarantine',
  'host-unquarantine',
  'ci-reconcile',
  'recall-spill',
])

const COMMAND_SCOPED_VERBS = new Set(['host-quarantine', 'host-unquarantine'])

function isActionDisabled(verb: string, host: FleetHost | null, pendingVerb: string | null): boolean {
  if (pendingVerb !== null) return true
  if (!SUPPORTED_OFFLOAD_VERBS.has(verb)) return true
  if (host !== null && host.registryState !== 'reachable') return true
  if (COMMAND_SCOPED_VERBS.has(verb)) {
    return host === null || !host.capability.missingCommand
  }
  if (HOST_SCOPED_VERBS.has(verb)) return host === null
  return false
}

function dispatchLabel(dispatch: OffloadControlModel['dispatch']): { text: string; intent: 'ok' | 'warn' | 'err' } {
  if (dispatch.state === 'healthy') return { text: 'healthy', intent: 'ok' }
  if (dispatch.state === 'wedged') {
    return {
      text: `wedged · ${dispatch.host ?? ''}${dispatch.detail ? ` ${dispatch.detail}` : ''}`.trim(),
      intent: 'err',
    }
  }
  return { text: dispatch.state, intent: 'warn' }
}

function leaseLabel(lease: OffloadControlModel['lease']): string {
  if (!lease.active) return 'none (remote-only)'
  if (lease.expired) return `expired${lease.host ? ` · ${lease.host}` : ''}`
  return lease.host ?? 'active'
}

/** Offload controller state-machine strip plus kv rows and capability probes. */
export function OffloadControl({
  control,
  selectedHost,
  onAction,
  pendingVerb,
  actionError,
}: OffloadControlProps) {
  const dispatch = dispatchLabel(control.dispatch)
  const spillOn = control.spill?.active
  const spillStale = control.spill?.stale

  return (
    <div data-testid="offload-control">
      <div className="mb-3 flex items-center gap-0">
        {FSM_STATES.map((state, index) => {
          const active = control.observed === state
          return (
            <div
              key={state}
              className={`flex-1 border border-border px-1 py-1.5 text-center text-[11px] ${
                index === 0 ? 'rounded-l-[7px]' : ''
              } ${index === FSM_STATES.length - 1 ? 'rounded-r-[7px] border-r' : 'border-r-0'} ${
                active ? 'border-accent bg-[#1d2433] font-bold text-[#dbe4ff]' : 'text-fg-subtle'
              }`}
            >
              {state}
            </div>
          )
        })}
      </div>

      <KvRow label="desired / observed" value={`${control.desired} / ${control.observed}`} intent="ok" />
      <KvRow label="revision" value={String(control.revision)} mono />
      <KvRow label="local-fallback lease" value={leaseLabel(control.lease)} intent={control.lease.expired ? 'err' : 'ok'} />
      <KvRow
        label="reconciler"
        value={control.reconciler.healthy ? 'healthy' : 'unhealthy'}
        intent={control.reconciler.healthy ? 'ok' : 'err'}
      />
      <KvRow label="dispatch" value={dispatch.text} intent={dispatch.intent} />
      <KvRow
        label="laptop spill"
        value={spillOn ? `ON${spillStale ? ' (stale)' : ''}` : 'off'}
        intent={spillOn ? 'warn' : 'neutral'}
      />
      <KvRow label="spill rule" value="all builders overloaded & queue > builders" dim />
      <div className="border-b border-[#1d2027] py-2 text-[12px] text-fg-muted">host capability</div>
      <div className="flex flex-wrap gap-1.5 py-2">
        <CapabilityProbeList probes={control.capabilityProbes} />
      </div>
      <div className="mt-2 text-[11.5px] text-fg-muted" data-testid="offload-selected-host">
        {selectedHost ? `selected host: ${selectedHost.host}` : 'no host selected'}
      </div>
      {actionError ? (
        <div role="alert" data-testid="offload-control-action-error" className="mt-2 text-[12px] text-danger">
          {actionError.message}
        </div>
      ) : null}
      <div className="mt-3 flex flex-wrap gap-1.5" data-testid="offload-control-actions">
        {control.actions.map((action) => {
          const disabled = isActionDisabled(action.verb, selectedHost, pendingVerb)
          const pending = pendingVerb === action.verb
          return (
            <button
              key={action.label}
              type="button"
              data-action-verb={action.verb}
              disabled={disabled}
              aria-busy={pending || undefined}
              onClick={() => {
                if (!disabled) onAction(action)
              }}
              className={
                action.danger
                  ? `rounded-[7px] border border-danger px-3 py-1 text-[11.5px] text-danger ${
                      disabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'
                    }`
                  : `rounded-[7px] border border-border-strong bg-surface-raised px-3 py-1 text-[11.5px] text-fg ${
                      disabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'
                    }`
              }
            >
              {pending ? 'Running…' : action.label}
            </button>
          )
        })}
      </div>
    </div>
  )
}

function KvRow({
  label,
  value,
  intent = 'neutral',
  mono,
  dim,
}: {
  label: string
  value: string
  intent?: 'ok' | 'warn' | 'err' | 'neutral'
  mono?: boolean
  dim?: boolean
}) {
  const valueClass =
    intent === 'ok'
      ? 'text-success'
      : intent === 'warn'
        ? 'text-warning'
        : intent === 'err'
          ? 'text-danger'
          : dim
            ? 'font-normal text-fg-subtle'
            : 'text-fg'
  return (
    <div className="flex justify-between border-b border-[#1d2027] py-[5px] text-[12px] text-fg-muted">
      <span>{label}</span>
      <b className={`font-medium tabular-nums ${valueClass} ${mono ? 'font-mono text-[11.5px]' : ''}`}>{value}</b>
    </div>
  )
}
