// Autonomous Agents page — create, manage, and monitor autonomous agent tasks

const { useState, useEffect, useCallback, useRef } = React;

function AgentsPage({ theme }) {
  const t = theme;
  const store = useStore();
  const [agents, setAgents] = useState([]);
  const [selectedAgent, setSelectedAgent] = useState(null);
  const [showCreate, setShowCreate] = useState(false);
  const [loading, setLoading] = useState(true);

  const fetchAgents = useCallback(() => {
    fetch('/api/agents', { credentials: 'include' })
      .then(r => r.json())
      .then(data => { if (Array.isArray(data)) setAgents(data); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  useEffect(() => { fetchAgents(); const iv = setInterval(fetchAgents, 10000); return () => clearInterval(iv); }, [fetchAgents]);

  // Listen for agent_run_complete via WS (store passes parsed msg directly)
  useEffect(() => {
    window.__agentRunHandler = (msg) => {
      if (msg && msg.type === 'agent_run_complete') fetchAgents();
    };
    return () => { delete window.__agentRunHandler; };
  }, [fetchAgents]);

  const handleRun = async (agentId) => {
    await fetch(`/api/agents/${agentId}/run`, { method: 'POST', credentials: 'include' });
    fetchAgents();
  };

  const handleStop = async (agentId) => {
    await fetch(`/api/agents/${agentId}/stop`, { method: 'POST', credentials: 'include' });
    fetchAgents();
  };

  const handleDelete = async (agentId) => {
    await fetch(`/api/agents/${agentId}`, { method: 'DELETE', credentials: 'include' });
    setSelectedAgent(null);
    fetchAgents();
  };

  const handleToggle = async (agentId, enabled) => {
    await fetch(`/api/agents/${agentId}`, {
      method: 'PATCH', credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ enabled: enabled ? 1 : 0 }),
    });
    fetchAgents();
  };

  if (selectedAgent) {
    return <AgentDetail theme={t} agentId={selectedAgent} onBack={() => setSelectedAgent(null)}
      onRun={handleRun} onStop={handleStop} onDelete={handleDelete} />;
  }

  return (
    <main style={{ flex: 1, background: t.chatBg, color: t.fg, fontFamily: t.fontSans, overflowY: "auto", minWidth: 0 }}>
      {/* Header */}
      <div style={{ padding: "24px 32px", borderBottom: `1px solid ${t.line}`, background: t.bg2, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div>
          <div style={{ fontFamily: t.fontDisplay, fontWeight: t.weightHeading, fontSize: 22, letterSpacing: -0.2, lineHeight: 1, marginBottom: 6 }}>Autonomous Agents</div>
          <div style={{ fontSize: 12, color: t.fg2, fontFamily: t.fontMono }}>
            {agents.length} agent{agents.length !== 1 ? 's' : ''} configured - {agents.filter(a => a.status === 'running').length} running
          </div>
        </div>
        <button onClick={() => setShowCreate(true)} style={{
          padding: "8px 16px", background: t.accent, color: t.bg, border: "none",
          borderRadius: t.radius, cursor: "pointer", fontSize: 12, fontFamily: t.fontSans, fontWeight: 600,
        }}>+ New Agent</button>
      </div>

      {/* Agent cards */}
      <div style={{ padding: "24px 32px" }}>
        {loading && <div style={{ color: t.fg3, fontSize: 13 }}>Loading...</div>}
        {!loading && agents.length === 0 && (
          <EmptyState theme={t} onCreateClick={() => setShowCreate(true)} />
        )}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(340px, 1fr))", gap: 16 }}>
          {agents.map(a => (
            <AgentCard key={a.id} agent={a} theme={t}
              onSelect={() => setSelectedAgent(a.id)}
              onRun={() => handleRun(a.id)}
              onStop={() => handleStop(a.id)}
              onToggle={(en) => handleToggle(a.id, en)} />
          ))}
        </div>
      </div>

      {showCreate && <CreateAgentModal theme={t} machines={store.machines} onClose={() => setShowCreate(false)} onCreated={() => { setShowCreate(false); fetchAgents(); }} />}
    </main>
  );
}

function EmptyState({ theme, onCreateClick }) {
  const t = theme;
  return (
    <div style={{ textAlign: "center", padding: "60px 20px", maxWidth: 440, margin: "0 auto" }}>
      <div style={{ marginBottom: 16, opacity: 0.4 }}>
        <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 8v4l3 3"/><circle cx="12" cy="12" r="9"/></svg>
      </div>
      <div style={{ fontFamily: t.fontDisplay, fontWeight: t.weightHeading, fontSize: 18, marginBottom: 8 }}>No autonomous agents yet</div>
      <div style={{ fontSize: 13, color: t.fg2, lineHeight: 1.6, marginBottom: 20 }}>
        Create agents that run tasks on your machines automatically. Trading bots, data pipelines, inbox triage, monitoring, and more.
      </div>
      <button onClick={onCreateClick} style={{
        padding: "10px 20px", background: t.accent, color: t.bg, border: "none",
        borderRadius: t.radius, cursor: "pointer", fontSize: 13, fontWeight: 600,
      }}>Create your first agent</button>
    </div>
  );
}

function connectorTooOld(ver) {
  const cv = (ver || '').replace('v', '').split('.').map(Number);
  return cv.length !== 3 || cv[0] < 1 || (cv[0] === 1 && cv[1] === 0 && cv[2] < 23);
}

function AgentCard({ agent, theme, onSelect, onRun, onStop, onToggle }) {
  const t = theme;
  const a = agent;
  const statusColor = a.status === 'running' ? t.accent : a.status === 'error' ? t.err : t.fg3;
  const scheduleLabel = a.schedule_type === 'interval' ? `Every ${formatInterval(a.schedule_interval)}` :
    a.schedule_type === 'cron' ? `Cron: ${a.schedule_cron}` : 'Manual';
  const oldConnector = connectorTooOld(a.connector_version);

  return (
    <div style={{ background: t.panel, border: `1px solid ${t.line}`, borderRadius: t.radius, padding: 16, display: "flex", flexDirection: "column", gap: 12 }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
        <div style={{
          width: 32, height: 32, borderRadius: t.radius, background: a.status === 'running' ? `${t.accent}20` : t.panel2,
          border: `1px solid ${a.status === 'running' ? t.accent + '40' : t.line2}`,
          display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={statusColor} strokeWidth="2"><path d="M12 8v4l3 3"/><circle cx="12" cy="12" r="9"/></svg>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: t.fg, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{a.name}</div>
          <div style={{ fontSize: 10.5, fontFamily: t.fontMono, color: t.fg3, marginTop: 2 }}>{a.machine_name} - {scheduleLabel}</div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ fontSize: 10, fontFamily: t.fontMono, color: statusColor, textTransform: "uppercase", letterSpacing: 0.6 }}>{a.status}</span>
          <StatusDot status={a.status === 'running' ? 'running' : a.status === 'error' ? 'error' : 'offline'} theme={t} />
        </div>
      </div>

      {oldConnector && (
        <div style={{ fontSize: 10.5, color: t.err, background: `${t.err}12`, padding: "6px 8px", borderRadius: t.radius, fontFamily: t.fontMono }}>
          Connector {a.connector_version || '?'} too old. Update to &gt;= 1.0.23
        </div>
      )}

      <div style={{ fontSize: 12, color: t.fg2, lineHeight: 1.5, overflow: "hidden", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" }}>
        {a.prompt.substring(0, 120)}{a.prompt.length > 120 ? '...' : ''}
      </div>

      <div style={{ display: "flex", gap: 8, fontSize: 10, fontFamily: t.fontMono, color: t.fg3 }}>
        <span>{a.total_runs || 0} runs</span>
        {a.last_run_at && <><span style={{ opacity: 0.5 }}>-</span><span>last {timeAgo(a.last_run_at)}</span></>}
      </div>

      <div style={{ display: "flex", gap: 6, borderTop: `1px solid ${t.line}`, paddingTop: 12 }}>
        {a.status === 'running' ? (
          <button onClick={(e) => { e.stopPropagation(); onStop(); }} style={btnStyle(t, t.err)}>Stop</button>
        ) : (
          <button onClick={(e) => { e.stopPropagation(); onRun(); }} style={btnStyle(t, t.accent)}
            disabled={a.machine_status !== 'online' || oldConnector}>Run</button>
        )}
        <button onClick={onSelect} style={btnStyle(t, null)}>Details</button>
        <div style={{ flex: 1 }} />
        <ToggleSwitch theme={t} enabled={!!a.enabled} onToggle={(v) => onToggle(v)} />
      </div>
    </div>
  );
}

function ToggleSwitch({ theme, enabled, onToggle }) {
  const t = theme;
  return (
    <button onClick={() => onToggle(!enabled)} style={{
      width: 36, height: 20, borderRadius: 10, border: "none", cursor: "pointer", padding: 2,
      background: enabled ? t.accent : t.line2, transition: "background 0.2s", display: "flex", alignItems: "center",
    }}>
      <div style={{
        width: 16, height: 16, borderRadius: 8, background: enabled ? t.bg : t.fg3,
        transform: enabled ? "translateX(16px)" : "translateX(0)", transition: "transform 0.2s",
      }} />
    </button>
  );
}

function btnStyle(t, color) {
  return {
    padding: "6px 12px", background: color ? `${color}18` : "transparent",
    border: `1px solid ${color || t.line2}`, borderRadius: t.radius,
    color: color || t.fg2, fontSize: 11, fontFamily: t.fontMono, cursor: "pointer",
  };
}

function formatInterval(seconds) {
  if (!seconds) return '?';
  if (seconds < 60) return `${seconds}s`;
  if (seconds < 3600) return `${Math.round(seconds / 60)}m`;
  if (seconds < 86400) return `${Math.round(seconds / 3600)}h`;
  return `${Math.round(seconds / 86400)}d`;
}

window.AgentsPage = AgentsPage;
