import { useCallback, useState } from 'react';
import { buildGoaAgentInjection, runGoaPipeline, shouldAutoRouteGoa } from '@/lib/goa-pipeline';
import { ptyWrite } from '@/lib/tauri-bridge';
import { useActiveWorkspace, useWorkbenchStore } from '@/features/workspace/WorkspaceStore';

const MAX_HISTORY = 12;

export function AgentPromptBar() {
  const mainAgentPtyId = useWorkbenchStore((s) => s.mainAgentPtyId);
  const comfortEnabled = useWorkbenchStore((s) => s.settings.comfortPromptEnabled ?? true);
  const goaAutoRoute = useWorkbenchStore((s) => s.settings.goaAutoRoute ?? true);
  const settings = useWorkbenchStore((s) => s.settings);
  const promptHistory = useWorkbenchStore((s) => s.promptHistory);
  const pushPromptHistory = useWorkbenchStore((s) => s.pushPromptHistory);
  const setToolsTab = useWorkbenchStore((s) => s.setToolsTab);
  const setServiceResult = useWorkbenchStore((s) => s.setServiceResult);
  const auth = useWorkbenchStore((s) => s.auth);
  const workspace = useActiveWorkspace();
  const [text, setText] = useState('');
  const [sending, setSending] = useState(false);
  const [goaStatus, setGoaStatus] = useState<string | null>(null);

  const sendToTerminal = useCallback(async () => {
    const trimmed = text.trim();
    if (!trimmed || !mainAgentPtyId) return;
    setSending(true);
    setGoaStatus(null);
    try {
      let goaLine = '';

      if (
        goaAutoRoute &&
        workspace?.rootPath &&
        shouldAutoRouteGoa(trimmed)
      ) {
        setGoaStatus('GOA pipeline running…');
        void setToolsTab('goa');
        const token = auth.hasToken ? await useWorkbenchStore.getState().getAuthToken() : null;
        const result = await runGoaPipeline({
          hyperloopUrl: settings.hyperloopUrl || 'https://hyperloop.vigthoria.io',
          templateUrl: settings.templateUrl || 'https://templates.vigthoria.io',
          token,
          workspaceRoot: workspace.rootPath,
          userPrompt: trimmed,
        });
        goaLine = buildGoaAgentInjection(result);
        setServiceResult(result.summary);
        setGoaStatus(
          result.executed
            ? `GOA ${result.payload.workspace_type} — executed`
            : `GOA ${result.payload.workspace_type} — architect only`,
        );
      }

      // The CLI's interactive readline reads ONE physical line per Enter
      // keypress (rl.question resolves as soon as it sees a newline). Writing
      // multiple newline-terminated lines straight to the PTY -- e.g. an
      // injected "@vigthoria-goa:{...}" context line followed by the actual
      // prompt, or a Shift+Enter multi-line prompt -- gets submitted as
      // several SEPARATE, unrelated inputs instead of one atomic prompt (the
      // GOA context line was even being misread as the task itself). Wrap any
      // multi-line payload in the CLI's own "{{{ ... }}}" block-mode markers
      // so `readMultiLineInput()` captures it as a single input, which the
      // CLI then correctly splits back apart via `splitGoaContextFromInput`.
      const fullBody = [goaLine, trimmed].filter(Boolean).join('\n');
      const payload = fullBody.includes('\n')
        ? `{{{\r\n${fullBody.replace(/\n/g, '\r\n')}\r\n}}}\r\n`
        : `${fullBody}\r\n`;
      await ptyWrite(mainAgentPtyId, payload);
      pushPromptHistory(trimmed);
      setText('');
    } catch (error) {
      // Previously any failure here (e.g. the GOA pipeline's network calls to
      // hyperloopUrl/templateUrl hanging or rejecting) silently discarded the
      // user's prompt: no catch meant the PTY write was skipped entirely and
      // the rejection was unhandled/invisible (2026-07-10 root-cause finding).
      // Fall back to sending the raw prompt so intent isn't lost, and surface
      // a visible error instead of doing nothing.
      const message = error instanceof Error ? error.message : String(error);
      setGoaStatus(`GOA pipeline failed (${message}) — sending prompt as-is`);
      try {
        await ptyWrite(mainAgentPtyId, `${trimmed}\r\n`);
        pushPromptHistory(trimmed);
        setText('');
      } catch (writeError) {
        const writeMessage = writeError instanceof Error ? writeError.message : String(writeError);
        setGoaStatus(`Failed to send prompt to terminal: ${writeMessage}`);
      }
    } finally {
      setSending(false);
    }
  }, [
    text,
    mainAgentPtyId,
    pushPromptHistory,
    goaAutoRoute,
    workspace?.rootPath,
    auth.hasToken,
    settings.hyperloopUrl,
    settings.templateUrl,
    setToolsTab,
    setServiceResult,
  ]);

  if (!comfortEnabled) {
    return (
      <div className="agent-prompt agent-prompt--disabled">
        <div className="agent-prompt__header">
          <span className="agent-prompt__title">Comfort prompt</span>
          <span className="agent-prompt__hint">Disabled in Settings → enable “Comfort prompt”.</span>
        </div>
      </div>
    );
  }

  return (
    <div className="agent-prompt">
      <div className="agent-prompt__header">
        <span className="agent-prompt__title">Comfort prompt</span>
        <span className="agent-prompt__hint">
          {auth.authenticated
            ? goaAutoRoute
              ? 'GOA auto-route ON — build/repair prompts run pipeline first, then Main Agent.'
              : 'Sends to Main Agent terminal (Enter). Shift+Enter = new line.'
            : 'Login first — prompts are disabled until authenticated.'}
        </span>
      </div>
      <textarea
        className="agent-prompt__input"
        rows={3}
        placeholder="Describe what the agent should do…"
        value={text}
        disabled={!mainAgentPtyId || !auth.authenticated || sending}
        onChange={(e) => setText(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            void sendToTerminal();
          }
        }}
      />
      <div className="agent-prompt__actions">
        <button
          type="button"
          className="agent-prompt__send"
          disabled={!text.trim() || !mainAgentPtyId || !auth.authenticated || sending}
          onClick={() => void sendToTerminal()}
        >
          {sending ? (goaStatus || 'Sending…') : 'Send to agent'}
        </button>
        {promptHistory.length > 0 && (
          <select
            className="agent-prompt__history"
            defaultValue=""
            onChange={(e) => {
              if (e.target.value) setText(e.target.value);
              e.target.value = '';
            }}
          >
            <option value="">Recent prompts…</option>
            {promptHistory.slice(0, MAX_HISTORY).map((item) => (
              <option key={item} value={item}>
                {item.length > 60 ? `${item.slice(0, 60)}…` : item}
              </option>
            ))}
          </select>
        )}
      </div>
    </div>
  );
}
