"use client";
import { useEffect, useState } from 'react';
import { subscribeAgentEvents } from './agent-events-bus.js';

export default function AgentRunButton({ agentId }) {
  const [running, setRunning] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    return subscribeAgentEvents((event) => {
      if (event.agent_id !== agentId) return;
      if (event.type === 'agent_run_start') setRunning(true);
      else if (event.type === 'agent_run_complete') setRunning(false);
    });
  }, [agentId]);

  async function onClick() {
    if (running || submitting) return;
    setSubmitting(true);
    setRunning(true); // optimistic — SSE will confirm or correct
    try {
      const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}/run`, {
        method: 'POST',
      });
      if (!res.ok) {
        // Roll back the optimistic flip — the run never started.
        setRunning(false);
      }
    } catch {
      setRunning(false);
    } finally {
      setSubmitting(false);
    }
  }

  const busy = running || submitting;
  return (
    <button
      type="button"
      className="admin-button"
      title={busy ? 'Agent is running' : 'Run now'}
      onClick={onClick}
      disabled={busy}
      aria-busy={busy || undefined}
    >
      {busy ? (
        <>
          <span className="agent-run-spinner" aria-hidden="true" />
          Running…
        </>
      ) : (
        'Run'
      )}
    </button>
  );
}
