/**
 * AgentChat — HoloLake 助手组件
 *
 * 通过受控工具协助用户管理 Git 驱动的知识库。
 * 支持：对话、工具调用展示、对话历史、清空对话。
 */

import { useState, useRef, useEffect } from 'react';
import { marked } from 'marked';

interface Message {
  role: 'user' | 'assistant' | 'tool' | 'system';
  content: string;
  toolCalls?: Array<{ id: string; name: string; arguments: Record<string, unknown> }>;
  toolResults?: Array<{ id: string; name: string; output: string; error?: string }>;
  timestamp: string;
}

interface AgentStatus {
  name: string;
  role: string;
  model: string;
  conversationLength: number;
  configured: boolean;
  operational: boolean;
  tools: string[];
}

interface PendingAction {
  id: string;
  tool: string;
  effect: 'write' | 'delete';
  target: string;
  summary: string;
  createdAt: string;
}

interface Props {
  apiBase: string;
  onDocSelect?: (path: string) => void;
  runtimeRevision?: number;
}

export default function AgentChat({ apiBase, onDocSelect, runtimeRevision = 0 }: Props) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const [status, setStatus] = useState<AgentStatus | null>(null);
  const [statusError, setStatusError] = useState('');
  const [pendingActions, setPendingActions] = useState<PendingAction[]>([]);
  const [actionBusy, setActionBusy] = useState('');
  const bottomRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    fetchStatus();
  }, [runtimeRevision]);

  useEffect(() => {
    if (messages.length > 0 || sending) {
      bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages, sending]);

  async function fetchStatus() {
    try {
      const res = await fetch(`${apiBase}/api/agent/status`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json();
      if (data.ok) {
        setStatusError('');
        setStatus({
          name: data.persona.name,
          role: data.persona.role,
          model: data.persona.model,
          conversationLength: data.conversationLength,
          configured: data.configured,
          operational: data.operational,
          tools: data.tools || [],
        });
      }
    } catch {
      setStatus(null);
      setStatusError('HoloLake 本地服务未启动');
    }
  }

  async function sendMessage() {
    const text = input.trim();
    if (!text || sending) return;

    setInput('');
    setSending(true);

    // 本地先显示用户消息
    const userMsg: Message = {
      role: 'user',
      content: text,
      timestamp: new Date().toISOString(),
    };
    setMessages(prev => [...prev, userMsg]);

    try {
      const res = await fetch(`${apiBase}/api/agent/chat`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: text }),
      });
      const data = await res.json();

      if (data.ok) {
        const assistantMsg: Message = {
          role: 'assistant',
          content: data.reply,
          timestamp: new Date().toISOString(),
        };
        setMessages(prev => [...prev, assistantMsg]);
        setPendingActions(data.pendingActions || []);
        fetchStatus(); // 刷新状态
      } else {
        setMessages(prev => [
          ...prev,
          { role: 'assistant', content: `错误: ${data.error}`, timestamp: new Date().toISOString() },
        ]);
      }
    } catch (err: any) {
      setMessages(prev => [
        ...prev,
        { role: 'assistant', content: `网络错误: ${err.message}`, timestamp: new Date().toISOString() },
      ]);
    } finally {
      setSending(false);
      inputRef.current?.focus();
    }
  }

  async function resolveAction(action: PendingAction, decision: 'confirm' | 'reject') {
    setActionBusy(action.id);
    try {
      const res = await fetch(`${apiBase}/api/agent/actions/${encodeURIComponent(action.id)}/${decision}`, {
        method: 'POST',
      });
      const data = await res.json();
      if (!data.ok) throw new Error(data.error || '动作处理失败');
      setPendingActions(data.actions || []);
      const content = decision === 'confirm'
        ? (data.result?.error ? `执行失败：${data.result.error}` : `已确认并执行：${data.result?.output || action.target}`)
        : `已取消：${action.summary}`;
      setMessages(prev => [...prev, { role: 'system', content, timestamp: new Date().toISOString() }]);
      fetchStatus();
    } catch (err: any) {
      setMessages(prev => [...prev, { role: 'system', content: `动作未执行：${err.message}`, timestamp: new Date().toISOString() }]);
    } finally {
      setActionBusy('');
    }
  }

  async function clearConversation() {
    try {
      await fetch(`${apiBase}/api/agent/clear`, { method: 'POST' });
      setMessages([]);
      fetchStatus();
    } catch {}
  }

  function handleKeyDown(e: React.KeyboardEvent) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  }

  return (
    <div className="agent-chat">
      {/* 头部状态栏 */}
      <div className="agent-header">
        <div className="agent-info">
          <div className="agent-avatar" aria-hidden="true"><span /></div>
          <div className="agent-meta">
            <h3>{status?.name || 'HoloLake'}</h3>
            <span className="agent-role">{status?.role || '语言操作入口'}</span>
          </div>
        </div>
        <div className="agent-actions">
          <span className="agent-model">{status?.model || 'offline'}</span>
          <button className="btn-clear" onClick={clearConversation} title="清空对话">
            ✕
          </button>
        </div>
      </div>

      <div className="runtime-status">
        <div className="runtime-row">
          <span className={`runtime-dot ${status?.operational ? 'online' : 'waiting'}`} />
          <span>{statusError || (status?.operational ? '语言操作入口可用' : status?.configured ? '模型已保存，等待连通验证' : '请在设置中配置模型')}</span>
          <span className="runtime-tools">{status?.tools?.length || 0} 项受控能力</span>
        </div>
      </div>

      {/* 对话区域 */}
      <div className="agent-messages">
        {messages.length === 0 && (
          <div className="agent-welcome">
            <h2>询问 HoloLake</h2>
            <p>{statusError || (status?.operational ? '可以检索、整理和编辑当前知识库，并为操作保留版本记录。' : '知识库可以独立使用；模型服务在设置中配置并验证。')}</p>
            <p className="welcome-hint">试试说：</p>
            <div className="welcome-suggestions">
              <button onClick={() => { setInput('帮我列出所有文档'); inputRef.current?.focus(); }}>
                列出所有文档
              </button>
              <button onClick={() => { setInput('搜索关于协议的内容'); inputRef.current?.focus(); }}>
                搜索关于协议的内容
              </button>
              <button onClick={() => { setInput('创建一篇新的学习笔记'); inputRef.current?.focus(); }}>
                创建学习笔记
              </button>
            </div>
          </div>
        )}

        {messages.map((msg, i) => (
          <div key={i} className={`msg msg-${msg.role}`}>
            {msg.role === 'user' ? (
              <div className="msg-bubble msg-user-bubble">
                <p>{msg.content}</p>
              </div>
            ) : (
              <div className="msg-bubble msg-assistant-bubble">
                <div className="msg-avatar" aria-hidden="true"><span /></div>
                <div className="msg-content">
                  {msg.toolCalls && msg.toolCalls.length > 0 && (
                    <div className="tool-calls">
                      {msg.toolCalls.map((tc, j) => (
                        <div key={j} className="tool-call">
                          <span className="tool-icon">运行</span>
                          <span className="tool-name">{tc.name}</span>
                          <code className="tool-args">{JSON.stringify(tc.arguments)}</code>
                        </div>
                      ))}
                    </div>
                  )}
                  {msg.toolResults && msg.toolResults.length > 0 && (
                    <div className="tool-results">
                      {msg.toolResults.map((tr, j) => (
                        <div key={j} className={`tool-result ${tr.error ? 'tool-error' : ''}`}>
                          <span className="tool-icon">{tr.error ? '失败' : '完成'}</span>
                          <pre>{tr.error || tr.output}</pre>
                        </div>
                      ))}
                    </div>
                  )}
                  <div
                    className="msg-markdown"
                    dangerouslySetInnerHTML={{
                      __html: marked.parse(msg.content, { async: false }) as string,
                    }}
                  />
                </div>
              </div>
            )}
          </div>
        ))}

        {pendingActions.length > 0 && (
          <div className="pending-actions" aria-label="待确认动作">
            <div className="pending-actions-heading">待确认动作</div>
            {pendingActions.map(action => (
              <div className={`pending-action ${action.effect}`} key={action.id}>
                <div>
                  <strong>{action.effect === 'delete' ? '删除' : '写入'} · {action.target}</strong>
                  <small>{action.summary}</small>
                </div>
                <div className="pending-action-buttons">
                  <button onClick={() => resolveAction(action, 'reject')} disabled={Boolean(actionBusy)}>取消</button>
                  <button className={action.effect === 'delete' ? 'danger' : 'confirm'} onClick={() => resolveAction(action, 'confirm')} disabled={Boolean(actionBusy)}>
                    {actionBusy === action.id ? '处理中…' : '确认执行'}
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}

        {sending && (
          <div className="msg msg-assistant">
            <div className="msg-bubble msg-assistant-bubble">
              <div className="msg-avatar" aria-hidden="true"><span /></div>
              <div className="msg-content typing">
                <span className="dot" />
                <span className="dot" />
                <span className="dot" />
              </div>
            </div>
          </div>
        )}
        <div ref={bottomRef} />
      </div>

      {/* 输入区 */}
      <div className="agent-input-area">
        <div className="agent-input-wrapper">
          <textarea
            ref={inputRef}
            className="agent-input"
            placeholder="向 HoloLake 发出语言指令…"
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            rows={1}
            disabled={sending || !status?.operational}
          />
          <button
            className="btn-send"
            onClick={sendMessage}
            disabled={sending || !input.trim() || !status?.operational}
          >
            {sending ? '⏳' : '↑'}
          </button>
        </div>
        <div className="agent-hint">
          {status?.operational ? 'Enter 发送 · 写操作先确认并由本地 Git 留痕 · 服务器推送独立确认' : '语言操作入口暂不可用；知识库仍可独立使用'}
        </div>
      </div>
    </div>
  );
}
