import { useState } from 'react'
import type { JSX } from 'react'
import { Button } from '@overdeck/deck-ui'
import { postCollectorAction } from '../../lib/action-client'

type StopState = 'idle' | 'confirming' | 'stopping' | 'stopped' | 'error'

export function FactoryStopButton(props: { adwId: string }): JSX.Element {
  const [state, setState] = useState<StopState>('idle')
  const [error, setError] = useState('')
  const [resultMessage, setResultMessage] = useState('')

  const stop = async () => {
    setState('stopping')
    try {
      const response = await postCollectorAction('factory.run.stop', {
        args: { adwId: props.adwId },
        requestedBy: 'deck-web',
      })
      setResultMessage(typeof response.result === 'string' ? response.result : '')
      setState('stopped')
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : 'stop failed')
      setState('error')
    }
  }

  if (state === 'stopped') {
    return (
      <p className="text-xs text-fg-muted" data-testid="factory-stop-done">
        {resultMessage || 'Stop requested — refreshing run status.'}
      </p>
    )
  }

  return (
    <div className="flex flex-wrap items-center gap-2" data-testid="factory-stop-controls">
      {state === 'confirming' ? (
        <>
          <span className="text-xs text-fg-muted">Stop this run? Its processes are killed and pending decisions canceled.</span>
          <Button variant="outline" tone="danger" size="sm" onClick={() => void stop()}>
            Yes, stop it
          </Button>
          <Button variant="outline" tone="neutral" size="sm" onClick={() => setState('idle')}>
            Keep running
          </Button>
        </>
      ) : (
        <Button
          variant="outline"
          tone="danger"
          size="sm"
          disabled={state === 'stopping'}
          onClick={() => setState('confirming')}
        >
          {state === 'stopping' ? 'Stopping…' : 'Stop run'}
        </Button>
      )}
      {state === 'error' ? <span className="text-xs text-danger">{error}</span> : null}
    </div>
  )
}
