/**
 * 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 RepositoryStatus {
  branch: string;
  head: string;
  clean: boolean;
  ahead: number;
  behind: number;
  remote: { name: string; url: string } | null;
}

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

export default function AgentChat({ apiBase, onDocSelect }: Props) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const [status, setStatus] = useState<AgentStatus | null>(null);
  const [repoStatus, setRepoStatus] = useState<RepositoryStatus | null>(null);
  const [remoteUrl, setRemoteUrl] = useState('');
  const [syncMessage, setSyncMessage] = useState('');
  const [syncing, setSyncing] = useState(false);
  const [configOpen, setConfigOpen] = useState(false);
  const [modelBaseUrl, setModelBaseUrl] = useState('https://api.openai.com/v1');
  const [modelName, setModelName] = useState('gpt-4o');
  const [modelKey, setModelKey] = useState('');
  const [configMessage, setConfigMessage] = useState('');
  const bottomRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);

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

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

  async function fetchStatus() {
    try {
      const res = await fetch(`${apiBase}/api/agent/status`);
      const data = await res.json();
      if (data.ok) {
        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 {}
  }

  async function loadModelConfig() {
    const bridge = (window as any).hololake?.agent;
    if (!bridge) return;
    try {
      const config = await bridge.getConfig();
      setModelBaseUrl(config.baseUrl || 'https://api.openai.com/v1');
      setModelName(config.model || 'gpt-4o');
    } catch {}
  }

  async function saveModelConfig() {
    const bridge = (window as any).hololake?.agent;
    if (!bridge) {
      setConfigMessage('模型安全配置只在桌面 App 中提供');
      return;
    }
    try {
      await bridge.saveConfig({ baseUrl: modelBaseUrl, model: modelName, apiKey: modelKey || undefined });
      setModelKey('');
      setConfigMessage('已保存到 macOS 加密存储');
      await fetchStatus();
    } catch (err: any) {
      setConfigMessage(err.message);
    }
  }

  async function fetchRepositoryStatus() {
    try {
      const res = await fetch(`${apiBase}/api/forgejo/status`);
      const data = await res.json();
      if (data.ok) {
        setRepoStatus(data.status);
        if (data.status.remote?.url) setRemoteUrl(data.status.remote.url);
      }
    } catch {}
  }

  async function runForgejoAction(action: 'configure' | 'fetch' | 'pull' | 'push') {
    if (syncing) return;
    if (action === 'push' && !confirm('确认把当前知识库提交推送到已配置的 Forgejo 仓库？')) return;
    setSyncing(true);
    setSyncMessage('');
    try {
      const endpoint = action === 'configure' ? 'remote' : action;
      const res = await fetch(`${apiBase}/api/forgejo/${endpoint}`, {
        method: action === 'configure' ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(action === 'configure' ? { url: remoteUrl } : { confirm: action === 'push' }),
      });
      const data = await res.json();
      if (!data.ok) throw new Error(data.error || '操作失败');
      setRepoStatus(data.status);
      setSyncMessage(action === 'configure' ? 'Forgejo 已连接' : `${action} 已完成`);
    } catch (err: any) {
      setSyncMessage(err.message);
    } finally {
      setSyncing(false);
    }
  }

  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]);
        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 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">🌊</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-config" onClick={() => setConfigOpen(!configOpen)} title="配置模型">⚙</button>
          <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>{status?.operational ? 'Agent 已接入模型' : 'Agent 等待模型配置'}</span>
          <span className="runtime-tools">{status?.tools?.length || 0} 个工具</span>
        </div>
        {configOpen && (
          <div className="model-config">
            <input value={modelBaseUrl} onChange={e => setModelBaseUrl(e.target.value)} placeholder="模型服务地址" />
            <input value={modelName} onChange={e => setModelName(e.target.value)} placeholder="模型名称" />
            <input type="password" value={modelKey} onChange={e => setModelKey(e.target.value)} placeholder={status?.configured ? '留空则保留现有密钥' : '模型密钥'} />
            <button onClick={saveModelConfig}>安全保存</button>
            {configMessage && <div className="forgejo-message">{configMessage}</div>}
          </div>
        )}
        <div className="forgejo-status">
          <div className="forgejo-title">
            <strong>Forgejo 代码引擎</strong>
            <span>{repoStatus?.remote ? `${repoStatus.branch} · ${repoStatus.head.slice(0, 7)}` : '尚未连接远端'}</span>
          </div>
          <input
            className="forgejo-url"
            value={remoteUrl}
            onChange={e => setRemoteUrl(e.target.value)}
            placeholder="HTTPS 或 SSH Forgejo 仓库地址"
          />
          <div className="forgejo-actions">
            <button onClick={() => runForgejoAction('configure')} disabled={syncing || !remoteUrl.trim()}>连接</button>
            <button onClick={() => runForgejoAction('fetch')} disabled={syncing || !repoStatus?.remote}>检查</button>
            <button onClick={() => runForgejoAction('pull')} disabled={syncing || !repoStatus?.remote}>拉取</button>
            <button onClick={() => runForgejoAction('push')} disabled={syncing || !repoStatus?.remote}>确认推送</button>
          </div>
          {repoStatus?.remote && (
            <div className="forgejo-detail">
              {repoStatus.clean ? '本地已提交' : '本地有未提交内容'} · 领先 {repoStatus.ahead} / 落后 {repoStatus.behind}
            </div>
          )}
          {syncMessage && <div className="forgejo-message">{syncMessage}</div>}
        </div>
      </div>

      {/* 对话区域 */}
      <div className="agent-messages">
        {messages.length === 0 && (
          <div className="agent-welcome">
            <div className="welcome-icon">🌊</div>
            <h2>HoloLake 助手</h2>
            <p>{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">🌊</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>
        ))}

        {sending && (
          <div className="msg msg-assistant">
            <div className="msg-bubble msg-assistant-bubble">
              <div className="msg-avatar">🌊</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 留痕 · Forgejo 推送需确认' : 'Agent 尚未接入模型；知识库与 Forgejo 功能仍可独立使用'}
        </div>
      </div>
    </div>
  );
}
