import React, { useState, useEffect } from 'react';
import axios from 'axios';

function ChatInterface() {
  const [message, setMessage] = useState('');
  const [chatHistory, setChatHistory] = useState([]);
  const [assistantType, setAssistantType] = useState('default');
  
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!message.trim()) return;
    
    // 添加用戶消息到歷史記錄
    const userMessage = { role: 'user', content: message };
    setChatHistory([...chatHistory, userMessage]);
    
    try {
      const response = await axios.post('/api/assistant/chat', {
        message: message,
        assistant_type: assistantType,
        context: {
          history: chatHistory
        }
      });
      
      // 添加助手回應到歷史記錄
      setChatHistory(prev => [...prev, { 
        role: 'assistant', 
        content: response.data.response 
      }]);
      
      setMessage('');
    } catch (error) {
      console.error('Error sending message:', error);
    }
  };
  
  return (
    <div className="chat-interface">
      <div className="assistant-selector">
        <select 
          value={assistantType} 
          onChange={(e) => setAssistantType(e.target.value)}
        >
          <option value="default">一般助手</option>
          <option value="code">程式碼助手</option>
          <option value="knowledge_graph">知識圖譜助手</option>
        </select>
      </div>
      
      <div className="chat-history">
        {chatHistory.map((msg, index) => (
          <div key={index} className={`message ${msg.role}`}>
            {msg.content}
          </div>
        ))}
      </div>
      
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          placeholder="輸入您的問題..."
        />
        <button type="submit">發送</button>
      </form>
    </div>
  );
}

export default ChatInterface; 