import React, { useEffect, useState, useRef } from 'react';
import { Input, Button, List, message, Modal, Form, Badge } from 'antd';
import { useNavigate } from 'react-router-dom';
import useAuthStore from '../store/authStore';
import api from '../services/api';
import ContactsView from '../components/ContactsView';
import GroupsView from '../components/GroupsView';
import SettingsView from '../components/SettingsView';
import EmojiPicker from '../components/EmojiPicker';
import { formatTimeToUTC8, formatSmartTime } from '../utils/timeUtils';
import './Dashboard.css';

const Dashboard = () => {
  const navigate = useNavigate();
  const { user, logout, token } = useAuthStore();
  const [activeNav, setActiveNav] = useState('chat');
  const [chatRooms, setChatRooms] = useState([]);
  const [friends, setFriends] = useState([]);
  const [activeRoom, setActiveRoom] = useState(null);
  const [activeRoomName, setActiveRoomName] = useState('');
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [ws, setWs] = useState(null);
  const [isRoomModalVisible, setIsRoomModalVisible] = useState(false);
  const [isFriendModalVisible, setIsFriendModalVisible] = useState(false);
  const [isAddMemberModalVisible, setIsAddMemberModalVisible] = useState(false);
  const [roomMembers, setRoomMembers] = useState([]);
  const [roomEmployees, setRoomEmployees] = useState([]);
  const [roomInfo, setRoomInfo] = useState(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [searchLoading, setSearchLoading] = useState(false);
  const messagesEndRef = useRef(null);
  
  // @提及功能相关状态
  const [showMentionList, setShowMentionList] = useState(false);
  const [mentionSearch, setMentionSearch] = useState('');
  const [mentionPosition, setMentionPosition] = useState(0);
  const inputRef = useRef(null);
  
  // 流式输出相关状态
  const [streamingMessage, setStreamingMessage] = useState(null); // { employeeName, content }
  const [isStreaming, setIsStreaming] = useState(false);
  
  // 表情选择器相关状态
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);

  useEffect(() => {
    if (!token) { 
      navigate('/login'); 
      return; 
    }
    
    // 如果有 token 但没有 user，获取用户信息
    if (!user) {
      fetchUserInfo();
    }
    
    fetchChatRooms();
    fetchFriends();
  }, [token, navigate]);

  const fetchUserInfo = async () => {
    try {
      const res = await api.get('/users/me');
      useAuthStore.getState().setAuth(res.data, token);
    } catch (e) {
      console.error('获取用户信息失败:', e);
      message.error('获取用户信息失败，请重新登录');
      logout();
      navigate('/login');
    }
  };

  const fetchChatRooms = async () => {
    try {
      const res = await api.get('/chatrooms/');
      setChatRooms(res.data);
    } catch (e) { console.error(e); }
  };

  const fetchFriends = async () => {
    try {
      const res = await api.get('/users/friends');
      setFriends(res.data);
    } catch (e) { console.error(e); }
  };

  const handleRoomSelect = async (room) => {
    // 检查用户是否已登录
    if (!user || !user.id) {
      message.error('用户信息未加载，请重新登录');
      navigate('/login');
      return;
    }

    setActiveRoom(room.id);
    setActiveRoomName(room.name);
    setActiveNav('chat');
    
    try {
      // 加载历史消息
      const res = await api.get(`/chatrooms/${room.id}/messages`);
      console.log('加载的历史消息:', res.data);
      setMessages(res.data);
      
      // 加载房间成员
      const membersRes = await api.get(`/chatrooms/${room.id}/members`);
      setRoomMembers(membersRes.data);
      
      // 加载房间中的数字员工
      try {
        const employeesRes = await api.get(`/chatrooms/${room.id}/employees`);
        setRoomEmployees(employeesRes.data);
      } catch (e) {
        console.error('加载数字员工失败:', e);
        setRoomEmployees([]);
      }
      
      // 加载房间信息
      setRoomInfo(room);
      
      // 建立 WebSocket 连接
      if (ws) ws.close();
      const wsBaseUrl = import.meta.env.VITE_WS_BASE_URL || 'ws://localhost:8000';
      const newWs = new WebSocket(`${wsBaseUrl}/ws/chat/${room.id}/${user.id}`);
      newWs.onmessage = (event) => {
        const msg = JSON.parse(event.data);
        console.log('收到新消息:', msg);
        setMessages((prev) => [...prev, msg]);
        
        // 如果收到的是数字员工的消息，清除流式消息显示
        if (msg.content && msg.content.startsWith('[AI-')) {
          setStreamingMessage(null);
          setIsStreaming(false);
        }
      };
      newWs.onerror = (error) => {
        console.error('WebSocket 错误:', error);
      };
      newWs.onclose = () => {
        console.log('WebSocket 连接已关闭');
      };
      setWs(newWs);
    } catch (e) {
      console.error('加载聊天室数据失败:', e);
      message.error(`加载失败: ${e.response?.data?.detail || e.message}`);
    }
  };

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

  // 处理输入框变化，检测@符号
  const handleInputChange = (e) => {
    const value = e.target.value;
    setInputValue(value);
    
    // 获取光标位置
    const cursorPos = e.target.selectionStart;
    
    // 查找最近的@符号位置
    const textBeforeCursor = value.substring(0, cursorPos);
    const lastAtIndex = textBeforeCursor.lastIndexOf('@');
    
    // 如果找到@符号，且@符号后面没有空格
    if (lastAtIndex !== -1) {
      const textAfterAt = textBeforeCursor.substring(lastAtIndex + 1);
      
      // 如果@后面没有空格，显示提及列表
      if (!textAfterAt.includes(' ')) {
        setMentionSearch(textAfterAt);
        setMentionPosition(lastAtIndex);
        setShowMentionList(true);
        return;
      }
    }
    
    // 否则隐藏提及列表
    setShowMentionList(false);
    setMentionSearch('');
  };
  
  // 选择数字员工
  const handleMentionSelect = (employee) => {
    // 获取@符号之前和之后的文本
    const beforeMention = inputValue.substring(0, mentionPosition);
    const afterMention = inputValue.substring(mentionPosition + 1 + mentionSearch.length);
    
    // 插入数字员工名称
    const newValue = `${beforeMention}@${employee.name} ${afterMention}`;
    setInputValue(newValue);
    
    // 隐藏提及列表
    setShowMentionList(false);
    setMentionSearch('');
    
    // 聚焦输入框
    setTimeout(() => {
      if (inputRef.current) {
        inputRef.current.focus();
        // 设置光标位置到插入的名称之后
        const newCursorPos = beforeMention.length + employee.name.length + 2; // +2 for @ and space
        inputRef.current.setSelectionRange(newCursorPos, newCursorPos);
      }
    }, 0);
  };
  
  // 处理键盘事件
  const handleKeyDown = (e) => {
    if (showMentionList && roomEmployees.length > 0) {
      // ESC键关闭列表
      if (e.key === 'Escape') {
        setShowMentionList(false);
        setMentionSearch('');
        e.preventDefault();
        return;
      }
      
      // Enter键选择第一个匹配项
      if (e.key === 'Enter' && !e.shiftKey) {
        const filtered = roomEmployees.filter(emp => 
          emp.name.toLowerCase().includes(mentionSearch.toLowerCase())
        );
        if (filtered.length > 0) {
          handleMentionSelect(filtered[0]);
          e.preventDefault();
          return;
        }
      }
    }
    
    // 正常的Enter发送消息
    if (e.key === 'Enter' && !e.shiftKey && !showMentionList) {
      sendMessage();
      e.preventDefault();
    }
  };

  // 流式输出文本
  const streamText = async (text, employeeName) => {
    setIsStreaming(true);
    setStreamingMessage({ employeeName, content: '' });
    
    const words = text.split('');
    let currentText = '';
    
    for (let i = 0; i < words.length; i++) {
      currentText += words[i];
      setStreamingMessage({ employeeName, content: currentText });
      
      // 控制流式输出速度（每个字符30ms）
      await new Promise(resolve => setTimeout(resolve, 30));
    }
    
    setIsStreaming(false);
    
    // 流式输出完成后，通过WebSocket发送完整消息
    return currentText;
  };

  // 处理表情选择
  const handleEmojiSelect = (content, type) => {
    if (type === 'emoji') {
      // Emoji表情直接插入到输入框
      setInputValue(prev => prev + content);
      setShowEmojiPicker(false);
      // 聚焦输入框
      setTimeout(() => {
        if (inputRef.current) {
          inputRef.current.focus();
        }
      }, 0);
    } else if (type === 'image') {
      // 图片表情直接发送
      if (ws && ws.readyState === WebSocket.OPEN) {
        const imageMessage = JSON.stringify({
          type: 'image',
          content: content
        });
        ws.send(imageMessage);
        setShowEmojiPicker(false);
      }
    }
  };

  const sendMessage = async () => {
    if (!inputValue.trim() || !ws) return;
    
    const currentMessage = inputValue;
    
    // 发送消息
    ws.send(currentMessage);
    setInputValue('');
    
    // 检测是否 @了数字员工
    const mentionPattern = /@(\S+)/g;
    const mentions = [...currentMessage.matchAll(mentionPattern)];
    
    if (mentions.length > 0 && roomEmployees.length > 0) {
      // 检查是否 @了数字员工
      for (const match of mentions) {
        const mentionedName = match[1];
        const employee = roomEmployees.find(emp => emp.name === mentionedName);
        
        if (employee) {
          // 调用数字员工回复 API
          try {
            const response = await api.post(`/chatrooms/${activeRoom}/employee_reply`, {
              employee_id: employee.id,
              message: currentMessage,
              user_name: user?.username
            });
            
            // 如果回复成功，使用流式输出显示
            if (response.data.success && response.data.reply) {
              // 等待一小段时间，让用户的消息先显示
              await new Promise(resolve => setTimeout(resolve, 500));
              
              // 构建完整的回复内容
              let fullReplyContent = response.data.reply;
              
              // 如果有工具调用，添加简化的工具调用信息
              if (response.data.tool_calls && response.data.tool_calls.length > 0) {
                fullReplyContent += '\n\n---\n🔧 调用了 ' + response.data.tool_calls.length + ' 个工具：';
                response.data.tool_calls.forEach((toolCall, index) => {
                  const statusIcon = toolCall.status === 'success' ? '✅' : '❌';
                  fullReplyContent += `\n${index + 1}. ${statusIcon} ${toolCall.tool_name}`;
                });
              }
              
              // 流式输出数字员工的回复
              const displayedReply = await streamText(fullReplyContent, employee.name);
              
              // 流式输出完成后，通过 WebSocket 发送完整消息
              const employeeReply = `[AI-${employee.name}] @${user?.username} ${fullReplyContent}`;
              
              setTimeout(() => {
                if (ws && ws.readyState === WebSocket.OPEN) {
                  ws.send(employeeReply);
                  // 注意：不在这里清除流式消息，而是在 onmessage 中收到消息后清除
                }
              }, 300);
            }
          } catch (e) {
            console.error('数字员工回复失败:', e);
            const errorMsg = e.response?.data?.detail || '数字员工回复失败，请稍后重试';
            message.error(errorMsg);
            setStreamingMessage(null);
            setIsStreaming(false);
          }
        }
      }
    }
  };

  const handleLogout = () => {
    logout();
    if (ws) ws.close();
    navigate('/login');
  };

  const handleCreateRoom = async (values) => {
    try {
      await api.post('/chatrooms/', { name: values.name });
      message.success('聊天室创建成功');
      setIsRoomModalVisible(false);
      fetchChatRooms();
    } catch (e) { message.error('创建聊天室失败'); }
  };

  const handleAddFriend = async (values) => {
    try {
      await api.post(`/users/friends/${values.username}`);
      message.success('好友添加成功');
      setIsFriendModalVisible(false);
      fetchFriends();
    } catch (e) { message.error('添加好友失败'); }
  };

  const handleSearchUsers = async (query) => {
    setSearchQuery(query);
    if (!query || query.length < 2) {
      setSearchResults([]);
      return;
    }
    
    setSearchLoading(true);
    try {
      const res = await api.get(`/users/search?q=${encodeURIComponent(query)}`);
      setSearchResults(res.data);
    } catch (e) {
      console.error('搜索用户失败:', e);
    } finally {
      setSearchLoading(false);
    }
  };

  const handleAddMemberToRoom = async (userId) => {
    if (!activeRoom) return;
    
    try {
      await api.post(`/chatrooms/${activeRoom}/add_user/${userId}`);
      message.success('成员添加成功');
      // 刷新成员列表
      const membersRes = await api.get(`/chatrooms/${activeRoom}/members`);
      setRoomMembers(membersRes.data);
      setIsAddMemberModalVisible(false);
      setSearchQuery('');
      setSearchResults([]);
    } catch (e) {
      const errorMsg = e.response?.data?.detail || '添加成员失败';
      message.error(errorMsg);
    }
  };

  const handleRemoveMember = (memberId, memberName) => {
    Modal.confirm({
      title: '确认移除成员',
      content: `确定要将 ${memberName} 移出群组吗？`,
      okText: '确定移除',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await api.delete(`/chatrooms/${activeRoom}/members/${memberId}`);
          message.success('成员已移除');
          // 刷新成员列表
          const membersRes = await api.get(`/chatrooms/${activeRoom}/members`);
          setRoomMembers(membersRes.data);
        } catch (e) {
          const errorMsg = e.response?.data?.detail || '移除失败';
          message.error(errorMsg);
        }
      }
    });
  };

  const handleRemoveEmployee = (employeeId, employeeName) => {
    Modal.confirm({
      title: '确认移除数字员工',
      content: `确定要将 ${employeeName} 移出群组吗？`,
      okText: '确定移除',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await api.delete(`/chatrooms/${activeRoom}/employees/${employeeId}`);
          message.success('数字员工已移除');
          // 刷新数字员工列表
          const employeesRes = await api.get(`/chatrooms/${activeRoom}/employees`);
          setRoomEmployees(employeesRes.data);
        } catch (e) {
          const errorMsg = e.response?.data?.detail || '移除失败';
          message.error(errorMsg);
        }
      }
    });
  };

  const navItems = [
    { key: 'chat', label: '会话', icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg> },
    { key: 'contacts', label: '联系人', icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/><circle cx="9" cy="7" r="4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg> },
    { key: 'groups', label: '群组', icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/><circle cx="9" cy="7" r="4" stroke="currentColor" strokeWidth="2"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg> },
    { key: 'models', label: '模型配置', icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2"/><path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg> },
    { key: 'ai', label: '智能体构建', icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><rect x="3" y="11" width="18" height="11" rx="2" stroke="currentColor" strokeWidth="2"/><path d="M7 11V7a5 5 0 0110 0v4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg> },
    { key: 'analytics', label: '数据分析', icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><line x1="18" y1="20" x2="18" y2="10" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/><line x1="12" y1="20" x2="12" y2="4" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/><line x1="6" y1="20" x2="6" y2="14" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg> },
    { key: 'settings', label: '设置', icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2"/><path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg> },
  ];

  // 渲染主内容区
  const renderMain = () => {
    // 联系人
    if (activeNav === 'contacts') {
      return (
        <ContactsView
          friends={friends}
          onRefresh={fetchFriends}
          onStartChat={(room) => {
            // 切换到聊天视图
            handleRoomSelect(room);
          }}
        />
      );
    }
    // 群组
    if (activeNav === 'groups') {
      return (
        <GroupsView
          chatRooms={chatRooms}
          friends={friends}
          onRefresh={fetchChatRooms}
          onEnterRoom={handleRoomSelect}
        />
      );
    }
    // 设置
    if (activeNav === 'settings') {
      return (
        <SettingsView
          user={user}
          onLogout={handleLogout}
        />
      );
    }
    if (activeRoom) {
      return (
        <div className="db-chat-container">
          <div className="db-chat-view">
            <div className="db-chat-header">
              <span className="db-chat-room-name">{activeRoomName}</span>
              <button className="db-chat-back" onClick={() => {
                setActiveRoom(null);
                setRoomMembers([]);
                setRoomInfo(null);
              }}>← 返回</button>
            </div>
            <div className="db-messages-area">
              {messages.length === 0 ? (
                <div className="db-empty-messages">
                  <svg width="48" height="48" viewBox="0 0 24 24" fill="none">
                    <path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" stroke="#d1d5db" strokeWidth="2"/>
                  </svg>
                  <p>暂无消息，开始聊天吧</p>
                </div>
              ) : (
                <List
                  dataSource={messages}
                  renderItem={(msg) => {
                    const isSelf = msg.sender_id === user?.id;
                    const isEmployee = msg.is_employee;
                    
                    // 调试日志
                    console.log('消息数据:', {
                      msg_sender_id: msg.sender_id,
                      user_id: user?.id,
                      isSelf: isSelf,
                      isEmployee: isEmployee,
                      content: msg.content
                    });
                    
                    return (
                      <List.Item style={{ border: 'none', padding: '8px 0', display: 'block' }}>
                        <div className={`db-msg-row ${isSelf ? 'db-msg-self' : 'db-msg-other'}`}>
                          {/* 左侧头像（其他人的消息） */}
                          {!isSelf && (
                            <div className={`db-msg-avatar ${isEmployee ? 'db-msg-avatar-ai' : ''}`}>
                              {isEmployee ? (
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                                  <circle cx="12" cy="12" r="3" stroke="white" strokeWidth="2"/>
                                  <path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="white" strokeWidth="2" strokeLinecap="round"/>
                                </svg>
                              ) : (
                                msg.sender_name?.[0]?.toUpperCase() || 'U'
                              )}
                            </div>
                          )}
                          
                          {/* 消息内容 */}
                          <div className="db-msg-content">
                            {/* 发送者名称（其他人的消息才显示） */}
                            {!isSelf && (
                              <div className="db-msg-sender-name">
                                {msg.sender_name}
                                {isEmployee && <span className="db-ai-badge-small">AI</span>}
                              </div>
                            )}
                            
                            {/* 消息气泡 */}
                            <div className={`db-msg-bubble ${isSelf ? 'db-msg-bubble-self' : ''} ${isEmployee ? 'db-msg-bubble-employee' : ''}`}>
                              {/* 根据消息类型渲染不同内容 */}
                              {msg.message_type === 'image' ? (
                                <div className="db-msg-image">
                                  <img src={msg.content} alt="表情" />
                                </div>
                              ) : isEmployee ? (
                                // 数字员工的消息以HTML方式渲染
                                <div 
                                  className="db-msg-text db-msg-html" 
                                  dangerouslySetInnerHTML={{ __html: msg.content }}
                                />
                              ) : (
                                // 普通用户消息以纯文本渲染
                                <div className="db-msg-text">{msg.content}</div>
                              )}
                              <div className="db-msg-time">
                                {formatSmartTime(msg.timestamp)}
                              </div>
                            </div>
                          </div>
                          
                          {/* 右侧头像（自己的消息） */}
                          {isSelf && (
                            <div className="db-msg-avatar db-msg-avatar-self">
                              {user?.username?.[0]?.toUpperCase() || 'M'}
                            </div>
                          )}
                        </div>
                      </List.Item>
                    );
                  }}
                />
              )}
              
              {/* 流式输出的消息 */}
              {streamingMessage && (
                <div className="db-msg-row db-msg-other db-streaming-msg">
                  <div className="db-msg-avatar db-msg-avatar-ai">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                      <circle cx="12" cy="12" r="3" stroke="white" strokeWidth="2"/>
                      <path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="white" strokeWidth="2" strokeLinecap="round"/>
                    </svg>
                  </div>
                  <div className="db-msg-content">
                    <div className="db-msg-sender-name">
                      {streamingMessage.employeeName}
                      <span className="db-ai-badge-small">AI</span>
                      {isStreaming && <span className="db-typing-indicator">正在输入...</span>}
                    </div>
                    <div className="db-msg-bubble db-msg-bubble-employee db-streaming-bubble">
                      <div 
                        className="db-msg-text db-msg-html" 
                        dangerouslySetInnerHTML={{ __html: streamingMessage.content }}
                      />
                      {isStreaming && <span className="db-cursor">|</span>}
                    </div>
                  </div>
                </div>
              )}
              
              <div ref={messagesEndRef} />
            </div>
            <div className="db-input-bar">
              {/* 表情选择器 */}
              {showEmojiPicker && (
                <EmojiPicker
                  onSelect={handleEmojiSelect}
                  onClose={() => setShowEmojiPicker(false)}
                />
              )}
              
              <div className="db-input-wrapper">
                {/* 表情按钮 */}
                <button
                  className="db-emoji-btn"
                  onClick={() => setShowEmojiPicker(!showEmojiPicker)}
                  title="选择表情"
                >
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                    <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2"/>
                    <path d="M8 14s1.5 2 4 2 4-2 4-2" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                    <circle cx="9" cy="9" r="1" fill="currentColor"/>
                    <circle cx="15" cy="9" r="1" fill="currentColor"/>
                  </svg>
                </button>
                
                <Input
                  ref={inputRef}
                  value={inputValue}
                  onChange={handleInputChange}
                  onKeyDown={handleKeyDown}
                  placeholder="输入消息，按 Enter 发送..."
                  className="db-msg-input"
                />
                {/* @提及下拉列表 */}
                {showMentionList && roomEmployees.length > 0 && (
                  <div className="db-mention-list">
                    {roomEmployees
                      .filter(emp => emp.name.toLowerCase().includes(mentionSearch.toLowerCase()))
                      .map(employee => (
                        <div
                          key={employee.id}
                          className="db-mention-item"
                          onClick={() => handleMentionSelect(employee)}
                        >
                          <div className="db-mention-avatar">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                              <circle cx="12" cy="12" r="3" stroke="white" strokeWidth="2"/>
                              <path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="white" strokeWidth="2" strokeLinecap="round"/>
                            </svg>
                          </div>
                          <div className="db-mention-info">
                            <div className="db-mention-name">{employee.name}</div>
                            <div className="db-mention-badge">AI助手</div>
                          </div>
                        </div>
                      ))}
                    {roomEmployees.filter(emp => emp.name.toLowerCase().includes(mentionSearch.toLowerCase())).length === 0 && (
                      <div className="db-mention-empty">未找到匹配的数字员工</div>
                    )}
                  </div>
                )}
              </div>
              <button className="db-send-btn" onClick={sendMessage}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M22 2L11 13M22 2L15 22l-4-9-9-4 20-7z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </button>
            </div>
          </div>

          {/* 右侧成员面板 */}
          <div className="db-chat-sidebar">
            {/* 成员列表 */}
            <div className="db-chat-section">
              <div className="db-chat-section-header">
                <span className="db-chat-section-title">
                  群成员 ({roomMembers.length})
                </span>
                <button 
                  className="db-chat-add-btn"
                  onClick={() => setIsAddMemberModalVisible(true)}
                  title="添加成员"
                >
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                    <line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                    <line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                  </svg>
                </button>
              </div>
              <div className="db-member-list">
                {roomMembers.map(member => (
                  <div key={member.id} className="db-member-item">
                    <div className="db-member-avatar">
                      {member.username?.[0]?.toUpperCase() || 'U'}
                    </div>
                    <div className="db-member-info">
                      <div className="db-member-name">{member.username}</div>
                      {roomInfo?.owner_id === member.id && (
                        <div className="db-member-badge">群主</div>
                      )}
                    </div>
                    {/* 只有群主可以移除成员，且不能移除自己 */}
                    {roomInfo?.owner_id === user?.id && member.id !== user?.id && (
                      <button
                        className="db-member-remove-btn"
                        onClick={() => handleRemoveMember(member.id, member.username)}
                        title="移除成员"
                      >
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                          <line x1="18" y1="6" x2="6" y2="18" stroke="currentColor" strokeWidth="2"/>
                          <line x1="6" y1="6" x2="18" y2="18" stroke="currentColor" strokeWidth="2"/>
                        </svg>
                      </button>
                    )}
                  </div>
                ))}
              </div>
            </div>

            {/* 数字员工列表 */}
            {roomEmployees.length > 0 && (
              <div className="db-chat-section">
                <div className="db-chat-section-header">
                  <span className="db-chat-section-title">
                    数字员工 ({roomEmployees.length})
                  </span>
                </div>
                <div className="db-member-list">
                  {roomEmployees.map(employee => (
                    <div key={employee.id} className="db-member-item db-employee-item">
                      <div className="db-member-avatar db-employee-avatar">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                          <circle cx="12" cy="12" r="3" stroke="white" strokeWidth="2"/>
                          <path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="white" strokeWidth="2" strokeLinecap="round"/>
                        </svg>
                      </div>
                      <div className="db-member-info">
                        <div className="db-member-name">{employee.name}</div>
                        <div className="db-employee-badge-small">AI助手</div>
                      </div>
                      <div className="db-employee-status">在线</div>
                      {/* 只有群主可以移除数字员工 */}
                      {roomInfo?.owner_id === user?.id && (
                        <button
                          className="db-member-remove-btn"
                          onClick={() => handleRemoveEmployee(employee.id, employee.name)}
                          title="移除数字员工"
                        >
                          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                            <line x1="18" y1="6" x2="6" y2="18" stroke="currentColor" strokeWidth="2"/>
                            <line x1="6" y1="6" x2="18" y2="18" stroke="currentColor" strokeWidth="2"/>
                          </svg>
                        </button>
                      )}
                    </div>
                  ))}
                </div>
                <div className="db-employee-hint">
                  💡 使用 @{roomEmployees[0]?.name} 来呼叫数字员工
                </div>
              </div>
            )}

            {/* 群组信息 */}
            {roomInfo && (
              <div className="db-chat-section">
                <div className="db-chat-section-header">
                  <span className="db-chat-section-title">群组信息</span>
                </div>
                <div className="db-room-detail">
                  <div className="db-room-detail-item">
                    <span className="db-room-detail-label">群组名称</span>
                    <span className="db-room-detail-value">{roomInfo.name}</span>
                  </div>
                  <div className="db-room-detail-item">
                    <span className="db-room-detail-label">群主</span>
                    <span className="db-room-detail-value">
                      {roomMembers.find(m => m.id === roomInfo.owner_id)?.username || '未知'}
                    </span>
                  </div>
                  <div className="db-room-detail-item">
                    <span className="db-room-detail-label">群组类型</span>
                    <span className="db-room-detail-value">
                      {roomInfo.is_private ? '私聊' : '群聊'}
                    </span>
                  </div>
                  <div className="db-room-detail-item">
                    <span className="db-room-detail-label">分享链接</span>
                    <button 
                      className="db-copy-link-btn"
                      onClick={() => {
                        const link = `${window.location.origin}/join/${roomInfo.share_link}`;
                        navigator.clipboard.writeText(link);
                        message.success('链接已复制');
                      }}
                    >
                      复制链接
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      );
    }

    return (
      <div className="db-home">
        {/* 欢迎语 */}
        <div className="db-welcome">
          <h2>欢迎回来，{user?.username}</h2>
          <p>当前有 {chatRooms.length} 个聊天室可用。</p>
        </div>

        <div className="db-home-grid">
          {/* 活跃聊天室 */}
          <div className="db-card db-rooms-card">
            <div className="db-card-header">
              <div className="db-card-title">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" stroke="#4f46e5" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                活跃聊天室
              </div>
              <button className="db-card-action" onClick={() => setIsRoomModalVisible(true)}>+ 新建</button>
            </div>
            <div className="db-room-list">
              {chatRooms.length === 0 ? (
                <div className="db-empty">暂无聊天室，点击新建创建一个</div>
              ) : (
                chatRooms.map(room => (
                  <div key={room.id} className="db-room-item" onClick={() => handleRoomSelect(room)}>
                    <div className="db-room-avatar">{room.name?.[0]?.toUpperCase() || 'R'}</div>
                    <div className="db-room-info">
                      <div className="db-room-name">{room.name}</div>
                      <div className="db-room-sub">点击进入聊天</div>
                    </div>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M9 18l6-6-6-6" stroke="#9ca3af" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* 联系人 */}
          <div className="db-card db-friends-card">
            <div className="db-card-header">
              <div className="db-card-title">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke="#4f46e5" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/><circle cx="9" cy="7" r="4" stroke="#4f46e5" strokeWidth="2"/></svg>
                联系人
              </div>
              <button className="db-card-action" onClick={() => setIsFriendModalVisible(true)}>+ 添加</button>
            </div>
            <div className="db-friend-list">
              {friends.length === 0 ? (
                <div className="db-empty">暂无联系人</div>
              ) : (
                friends.map(f => (
                  <div key={f.id} className="db-friend-item">
                    <div className="db-friend-avatar">{f.friend?.username?.[0]?.toUpperCase() || 'U'}</div>
                    <div className="db-friend-info">
                      <div className="db-friend-name">{f.friend?.username}</div>
                      {f.alias && <div className="db-friend-alias">{f.alias}</div>}
                    </div>
                    <div className="db-online-dot" />
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="db-root">
      {/* 左侧导航 */}
      <aside className="db-sidebar">
        <div className="db-sidebar-logo">
          <div className="db-logo-icon">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </div>
          <span className="db-logo-text">灵犀智能</span>
          <span className="db-logo-sub">EDITORIAL INTELLIGENCE</span>
        </div>

        <nav className="db-nav">
          {navItems.map(item => (
            <button
              key={item.key}
              className={`db-nav-item ${activeNav === item.key ? 'db-nav-active' : ''}`}
              onClick={() => { setActiveNav(item.key); if (item.key !== 'chat') setActiveRoom(null); }}
            >
              <span className="db-nav-icon">{item.icon}</span>
              <span>{item.label}</span>
            </button>
          ))}
        </nav>

        <div className="db-sidebar-bottom">
          <button className="db-nav-item db-nav-logout" onClick={handleLogout}>
            <span className="db-nav-icon">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </span>
            <span>退出</span>
          </button>
        </div>
      </aside>

      {/* 主内容 */}
      <main className="db-main">
        {/* 顶部搜索栏 */}
        <header className="db-topbar">
          <div className="db-search-wrap">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" className="db-search-icon"><circle cx="11" cy="11" r="8" stroke="#9ca3af" strokeWidth="2"/><path d="M21 21l-4.35-4.35" stroke="#9ca3af" strokeWidth="2" strokeLinecap="round"/></svg>
            <input className="db-search-input" placeholder="搜索会话或功能..." />
          </div>
          <div className="db-topbar-right">
            <button className="db-icon-btn">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 01-3.46 0" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
              <span className="db-badge">3</span>
            </button>
            <button className="db-icon-btn">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2"/><path d="M9.09 9a3 3 0 015.83 1c0 2-3 3-3 3M12 17h.01" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
            <div className="db-user-info">
              <div className="db-user-avatar">{user?.username?.[0]?.toUpperCase() || 'U'}</div>
              <div>
                <div className="db-user-name">{user?.username}</div>
                <div className="db-user-role">普通用户</div>
              </div>
            </div>
          </div>
        </header>

        <div className="db-content">
          {renderMain()}
        </div>
      </main>

      {/* 右侧面板 */}
      <aside className="db-right-panel">
        {/* 私信 */}
        <div className="db-panel-section">
          <div className="db-panel-header">
            <div className="db-panel-title">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" stroke="#4f46e5" strokeWidth="2"/><polyline points="22,6 12,13 2,6" stroke="#4f46e5" strokeWidth="2"/></svg>
              私信
            </div>
            <button className="db-panel-add">+</button>
          </div>
          <div className="db-dm-list">
            {friends.slice(0, 3).map((f, i) => (
              <div key={f.id} className="db-dm-item">
                <div className="db-dm-avatar">{f.friend?.username?.[0]?.toUpperCase() || 'U'}</div>
                <div className="db-dm-info">
                  <div className="db-dm-name">{f.friend?.username}</div>
                  <div className="db-dm-time">{i === 0 ? '在线' : `${(i + 1) * 15}分钟前`}</div>
                </div>
                {i === 0 && <span className="db-dm-badge">2</span>}
              </div>
            ))}
            {friends.length === 0 && (
              <div className="db-empty-sm">暂无联系人</div>
            )}
          </div>
        </div>

        {/* 智能洞察 */}
        <div className="db-panel-section">
          <div className="db-panel-header">
            <div className="db-panel-title">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="#4f46e5" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
              智能洞察
            </div>
          </div>
          <div className="db-insight-card db-insight-tip">
            <div className="db-insight-tag">效率提醒</div>
            <p>您今日已参与 {chatRooms.length} 个会话，保持良好的沟通节奏。</p>
          </div>
          <div className="db-insight-card db-insight-ai">
            <div className="db-insight-tag">AI 建议</div>
            <p>尝试使用智能体构建功能，自动处理常见问题，提升响应效率。</p>
            <div className="db-insight-actions">
              <button className="db-insight-btn-primary">立即体验</button>
              <button className="db-insight-btn-ghost">暂不处理</button>
            </div>
          </div>
        </div>
      </aside>

      {/* 新建聊天室 */}
      <Modal title="新建聊天室" open={isRoomModalVisible} onCancel={() => setIsRoomModalVisible(false)} footer={null}>
        <Form onFinish={handleCreateRoom} layout="vertical">
          <Form.Item name="name" label="聊天室名称" rules={[{ required: true, message: '请输入名称' }]}>
            <Input placeholder="输入聊天室名称" />
          </Form.Item>
          <Button type="primary" htmlType="submit" block>创建</Button>
        </Form>
      </Modal>

      {/* 添加好友 */}
      <Modal title="添加联系人" open={isFriendModalVisible} onCancel={() => setIsFriendModalVisible(false)} footer={null}>
        <Form onFinish={handleAddFriend} layout="vertical">
          <Form.Item name="username" label="用户名" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input placeholder="输入对方用户名" />
          </Form.Item>
          <Button type="primary" htmlType="submit" block>添加</Button>
        </Form>
      </Modal>

      {/* 添加群成员 */}
      <Modal 
        title="添加群成员" 
        open={isAddMemberModalVisible} 
        onCancel={() => {
          setIsAddMemberModalVisible(false);
          setSearchQuery('');
          setSearchResults([]);
        }} 
        footer={null}
        width={500}
      >
        <div className="db-add-member-modal">
          <Input
            placeholder="搜索用户名或邮箱..."
            value={searchQuery}
            onChange={(e) => handleSearchUsers(e.target.value)}
            prefix={
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                <circle cx="11" cy="11" r="8" stroke="#9ca3af" strokeWidth="2"/>
                <path d="M21 21l-4.35-4.35" stroke="#9ca3af" strokeWidth="2" strokeLinecap="round"/>
              </svg>
            }
            style={{ marginBottom: 16 }}
          />
          
          {searchLoading && (
            <div className="db-search-loading">搜索中...</div>
          )}
          
          {!searchLoading && searchResults.length === 0 && searchQuery.length >= 2 && (
            <div className="db-search-empty">未找到匹配的用户</div>
          )}
          
          {!searchLoading && searchResults.length > 0 && (
            <div className="db-search-results">
              {searchResults.map(user => {
                const isMember = roomMembers.some(m => m.id === user.id);
                return (
                  <div key={user.id} className="db-search-result-item">
                    <div className="db-search-user-avatar">
                      {user.username?.[0]?.toUpperCase() || 'U'}
                    </div>
                    <div className="db-search-user-info">
                      <div className="db-search-user-name">{user.username}</div>
                      <div className="db-search-user-email">{user.email}</div>
                    </div>
                    {isMember ? (
                      <span className="db-already-member">已在群组</span>
                    ) : (
                      <Button 
                        type="primary" 
                        size="small"
                        onClick={() => handleAddMemberToRoom(user.id)}
                      >
                        添加
                      </Button>
                    )}
                  </div>
                );
              })}
            </div>
          )}
          
          {searchQuery.length < 2 && (
            <div className="db-search-hint">
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none">
                <circle cx="11" cy="11" r="8" stroke="#d1d5db" strokeWidth="2"/>
                <path d="M21 21l-4.35-4.35" stroke="#d1d5db" strokeWidth="2" strokeLinecap="round"/>
              </svg>
              <p>输入至少 2 个字符开始搜索</p>
            </div>
          )}
        </div>
      </Modal>
    </div>
  );
};

export default Dashboard;
