import React, { useState, useEffect, useRef, useCallback } from 'react'
import { BsSearch } from 'react-icons/bs'
import './index.css'
import Login from './components/Login'
import ContactList from './components/ContactList'
import AppMappingList from './components/AppMappingList'
import { Navigation } from './components/Navigation'
import { SettingsModal } from './components/Modals/SettingsModal'
import { ChatPage } from './pages/ChatPage'
import { useAuth } from './hooks/useAuth'
import { useContacts } from './hooks/useContacts'
import { useMessages } from './hooks/useMessages'
import { useWebSocket } from './hooks/useWebSocket'
import { UserContact, api } from './services/api'
import { logger } from './utils/logger'
import { formatFullDateTime } from './utils/timeUtils'
import { isNotificationLikeMessage, isMessageFromSelf } from './utils/messageTypes'
import { getDefaultAvatar, getSessionAvatar } from './utils/avatarUtils'
import { Contact, Message, SearchResult } from './types'

function App(): JSX.Element {
  const {
    isLoggedIn,
    token,
    currentUserId,
    currentUserName,
    handleLogin,
    handleLogout,
    isRestoringSession,
    sessionExpiredMessage
  } = useAuth()
  const [activeTab, setActiveTab] = useState<'chat' | 'contact' | 'browser'>('chat')
  const [activeContactId, setActiveContactId] = useState<number | null>(null)
  const activeContactIdRef = useRef(activeContactId)
  const [selectedContactDetail, setSelectedContactDetail] = useState<UserContact | null>(null)
  const [showSettings, setShowSettings] = useState(false)
  const [showChatSearchModal, setShowChatSearchModal] = useState(false)
  const [inputValue, setInputValue] = useState('')
  const [contextMenu, setContextMenu] = useState<{ x: number, y: number, msgId: number } | null>(null)
  
  // 搜索相关状态
  const [searchQuery, setSearchQuery] = useState('')
  const [searchResults, setSearchResults] = useState<SearchResult[]>([])
  const [isSearching, setIsSearching] = useState(false)
  const searchTimeoutRef = useRef<NodeJS.Timeout | null>(null)
  const [chatSearchQuery, setChatSearchQuery] = useState('')
  const [chatSearchResults, setChatSearchResults] = useState<Message[]>([])
  
  const unreadCountsRef = useRef<Record<number, number>>({})

  useEffect(() => {
    if (!isLoggedIn) {
      setActiveContactId(null)
      setSelectedContactDetail(null)
      setActiveTab('chat')
      setSearchQuery('')
      setSearchResults([])
      setIsSearching(false)
      setChatSearchQuery('')
      setChatSearchResults([])
      setInputValue('')
      setContextMenu(null)
      unreadCountsRef.current = {}
    }
  }, [isLoggedIn])
  
  useEffect(() => {
    activeContactIdRef.current = activeContactId
  }, [activeContactId])

  const {
    contacts,
    setContacts,
    contactsRef,
    isLoadingContacts,
    fetchContacts
  } = useContacts(token, unreadCountsRef, activeContactId, setActiveContactId)

  const {
    messages,
    setMessages,
    isLoadingMessages,
    uploadProgress,
    sendMessage: sendMessageHook,
    sendFileMessage,
    loadedContacts
  } = useMessages(token, currentUserId, activeContactId, setContacts, unreadCountsRef)

  useWebSocket({
    isLoggedIn,
    token,
    currentUserId,
    activeContactId,
    activeContactIdRef,
    contactsRef,
    setMessages,
    setContacts,
    unreadCountsRef,
    fetchContacts
  })

  // 监听切换联系人事件
  useEffect(() => {
    const handleSwitchContact = (_: any, contactId: number) => {
      setActiveTab('chat')
      setActiveContactId(contactId)
      unreadCountsRef.current[contactId] = 0
      setContacts(prev => prev.map(c => c.id === contactId ? { ...c, unreadCount: 0 } : c))
    }

    if (window.electron && window.electron.ipcRenderer) {
      window.electron.ipcRenderer.on('switch-contact', handleSwitchContact)
    }

    return () => {
      if (window.electron && window.electron.ipcRenderer) {
        window.electron.ipcRenderer.removeAllListeners('switch-contact')
      }
    }
  }, [setContacts])

  // 切换标签页时，如果离开通讯录，清除选中的联系人详情
  useEffect(() => {
    if (activeTab !== 'contact' && selectedContactDetail) {
      setSelectedContactDetail(null)
    }
  }, [activeTab, selectedContactDetail])

  // 处理发送消息
  const handleSend = useCallback(async () => {
    if (!activeContactId) return
    await sendMessageHook(inputValue, activeContactId)
    setInputValue('')
  }, [inputValue, activeContactId, sendMessageHook])

  // 处理文件选择
  const handleFileSelect = useCallback((file: File) => {
    if (!activeContactId) return
    const contentType = api.getContentType(file) as 'IMAGE' | 'VIDEO' | 'FILE'
    sendFileMessage(file, contentType, activeContactId)
  }, [activeContactId, sendFileMessage])

  // 全局搜索
  const handleSearch = useCallback(async (query: string) => {
    if (!query.trim()) {
      setSearchResults([])
      return
    }
    
    setIsSearching(true)
    const queryLower = query.toLowerCase()
    const results: SearchResult[] = []
    
    const MAX_CONCURRENT = 3
    const contactsToLoad = contacts.filter(contact => !loadedContacts.has(contact.id))
    
    for (let i = 0; i < contactsToLoad.length; i += MAX_CONCURRENT) {
      const batch = contactsToLoad.slice(i, i + MAX_CONCURRENT)
      
      await Promise.allSettled(
        batch.map(async (contact) => {
          const contactId = contact.id
          if (!token) return
          
          try {
            const messagesData = await api.getMessages(token, contactId, {
              skip: 0,
              limit: 50
            })
            
            const formattedMessages: Message[] = messagesData.map(msg => {
              const notificationLike = isNotificationLikeMessage(msg.type, msg.content_type)
              const isSelf = isMessageFromSelf(msg, currentUserId)
              
              let messageType: 'text' | 'image' | 'file' | 'video' | 'notification' = 'text'
              if (notificationLike) {
                messageType = 'notification'
              } else if (msg.content_type === 'IMAGE') {
                messageType = 'image'
              } else if (msg.content_type === 'VIDEO') {
                messageType = 'video'
              } else if (msg.content_type === 'FILE') {
                messageType = 'file'
              }
              
              return {
                id: msg.id,
                content: msg.content || msg.title || '',
                isSelf: isSelf,
                type: messageType,
                timestamp: new Date(msg.created_at).getTime(),
                title: msg.title,
                actionUrl: msg.action_url,
                actionText: msg.action_text,
                messageType: msg.type,
                content_type: msg.content_type,
                size: (msg as any).size
              }
            })
            
            formattedMessages.sort((a, b) => a.timestamp - b.timestamp)
            
            setMessages(prev => ({
              ...prev,
              [contactId]: formattedMessages
            }))
          } catch (error) {
            logger.error('App: Failed to load messages for search', { contactId, error })
          }
        })
      )
      
      if (i + MAX_CONCURRENT < contactsToLoad.length) {
        await new Promise(resolve => setTimeout(resolve, 100))
      }
    }
    
    for (const contact of contacts) {
      const contactId = contact.id
      const contactMessages = messages[contactId] || []
      
      contactMessages.forEach(msg => {
        let matched = false
        if (
          (msg.type === 'text' || msg.type === 'notification') &&
          msg.content.toLowerCase().includes(queryLower)
        ) {
          matched = true
        }
        if (msg.title && msg.title.toLowerCase().includes(queryLower)) {
          matched = true
        }
        
        if (matched) {
          results.push({
            message: msg,
            contactId: contactId,
            contactName: contact.name
          })
        }
      })
    }
    
    results.sort((a, b) => b.message.timestamp - a.message.timestamp)
    setSearchResults(results)
    setIsSearching(false)
  }, [messages, contacts, loadedContacts, token, currentUserId, setMessages])

  // 聊天界面内的搜索
  const handleChatSearch = useCallback((query: string) => {
    if (!query.trim() || !activeContactId) {
      setChatSearchResults([])
      return
    }
    
    const queryLower = query.toLowerCase()
    const contactMessages = messages[activeContactId] || []
    const results = contactMessages.filter(msg => {
      if (
        (msg.type === 'text' || msg.type === 'notification') &&
        msg.content.toLowerCase().includes(queryLower)
      ) {
        return true
      }
      if (msg.title && msg.title.toLowerCase().includes(queryLower)) {
        return true
      }
      return false
    })
    
    setChatSearchResults(results)
  }, [messages, activeContactId])

  useEffect(() => {
    handleChatSearch(chatSearchQuery)
  }, [chatSearchQuery, handleChatSearch])

  // 处理从联系人详情页发送消息
  const handleSendMessageFromContact = (contact: UserContact) => {
    logger.info('App: Send message from contact detail', { contactId: contact.id, contactName: contact.name })
    
    setActiveTab('chat')
    setSelectedContactDetail(null)
    
    const existingContact = contacts.find(c => c.id === contact.id)
    
    if (existingContact) {
      setActiveContactId(contact.id)
      unreadCountsRef.current[contact.id] = 0
      setContacts(prev => prev.map(c => 
        c.id === contact.id ? { ...c, unreadCount: 0 } : c
      ))
    } else {
      unreadCountsRef.current[contact.id] = 0
      
      const newContact: Contact = {
        id: contact.id,
        name: contact.name || contact.english_name || `用户${contact.id}`,
        avatar: getSessionAvatar(contact.id, contact.name || contact.english_name, 40),
        lastMessage: undefined,
        lastMessageTime: undefined,
        unreadCount: 0
      }
      
      setContacts(prev => [newContact, ...prev])
      setActiveContactId(contact.id)
    }
  }

  // 处理右键菜单
  const handleContextMenu = (e: React.MouseEvent, msgId: number) => {
    e.preventDefault()
    setContextMenu({ x: e.clientX, y: e.clientY, msgId })
  }

  useEffect(() => {
    const handleClick = () => setContextMenu(null)
    document.addEventListener('click', handleClick)
    return () => document.removeEventListener('click', handleClick)
  }, [])

  const activeContact = contacts.find(c => c.id === activeContactId)
  const totalUnread = contacts.reduce((sum, c) => sum + c.unreadCount, 0)

  // 渲染中间列表区域
  const renderListPanel = () => {
    if (activeTab === 'chat') {
      return (
        <>
          <div className="search-bar" style={{ WebkitAppRegion: 'drag', position: 'relative', zIndex: 1 } as React.CSSProperties}>
            <div style={{ backgroundColor: '#e2e2e2', borderRadius: '4px', padding: '6px 8px', fontSize: '12px', color: '#666', display: 'flex', alignItems: 'center', WebkitAppRegion: 'no-drag', position: 'relative' } as React.CSSProperties}>
              <BsSearch style={{ marginRight: '5px' }} />
              <input
                type="text"
                placeholder="搜索聊天记录"
                value={searchQuery}
                onChange={(e) => {
                  const value = e.target.value
                  setSearchQuery(value)
                  
                  if (searchTimeoutRef.current) {
                    clearTimeout(searchTimeoutRef.current)
                  }
                  
                  if (!value.trim()) {
                    setSearchResults([])
                    setIsSearching(false)
                    return
                  }
                  
                  setIsSearching(true)
                  searchTimeoutRef.current = setTimeout(() => {
                    handleSearch(value)
                  }, 500)
                }}
                onClick={(e) => e.stopPropagation()}
                onFocus={(e) => e.stopPropagation()}
                style={{
                  border: 'none',
                  outline: 'none',
                  backgroundColor: 'transparent',
                  flex: 1,
                  fontSize: '12px',
                  color: '#666'
                }}
              />
              {searchQuery && (
                <span
                  onClick={(e) => {
                    e.stopPropagation()
                    setSearchQuery('')
                  }}
                  style={{ cursor: 'pointer', marginLeft: '5px', fontSize: '14px' }}
                >
                  ✕
                </span>
              )}
            </div>
            {searchQuery && searchResults.length > 0 && (
              <div 
                onClick={(e) => e.stopPropagation()}
                style={{
                  position: 'absolute',
                  top: '100%',
                  left: '10px',
                  right: '10px',
                  backgroundColor: '#fff',
                  border: '1px solid #e7e7e7',
                  borderRadius: '4px',
                  maxHeight: '300px',
                  overflowY: 'auto',
                  zIndex: 10000,
                  marginTop: '4px',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
                  WebkitAppRegion: 'no-drag'
                } as React.CSSProperties}
              >
                {searchResults.map((result, index) => (
                  <div
                    key={`${result.contactId}-${result.message.id}-${index}`}
                    onClick={(e) => {
                      e.preventDefault()
                      e.stopPropagation()
                      setActiveContactId(result.contactId)
                      setActiveTab('chat')
                      setSearchQuery('')
                      setTimeout(() => {
                        const messageElement = document.querySelector(`[data-message-id="${result.message.id}"]`)
                        if (messageElement) {
                          messageElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
                          ;(messageElement as HTMLElement).style.backgroundColor = '#fff3cd'
                          setTimeout(() => {
                            ;(messageElement as HTMLElement).style.backgroundColor = ''
                          }, 2000)
                        }
                      }, 300)
                    }}
                    style={{
                      padding: '8px 12px',
                      cursor: 'pointer',
                      borderBottom: '1px solid #f0f0f0',
                      fontSize: '12px'
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.backgroundColor = '#f5f5f5'
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.backgroundColor = '#fff'
                    }}
                  >
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
                      <div style={{ color: '#666', fontSize: '11px', fontWeight: '500' }}>
                        {result.contactName}
                      </div>
                      <div style={{ color: '#999', fontSize: '10px' }}>
                        {formatFullDateTime(result.message.timestamp)}
                      </div>
                    </div>
                    <div style={{ 
                      color: '#333',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap'
                    }}>
                      {result.message.type === 'text' ? result.message.content : `[${result.message.type === 'image' ? '图片' : result.message.type === 'file' ? '文件' : result.message.type === 'video' ? '视频' : '通知'}] ${result.message.title || ''}`}
                    </div>
                  </div>
                ))}
              </div>
            )}
            {searchQuery && searchResults.length === 0 && !isSearching && (
              <div 
                onClick={(e) => e.stopPropagation()}
                style={{
                  position: 'absolute',
                  top: '100%',
                  left: '10px',
                  right: '10px',
                  backgroundColor: '#fff',
                  border: '1px solid #e7e7e7',
                  borderRadius: '4px',
                  padding: '12px',
                  textAlign: 'center',
                  color: '#999',
                  fontSize: '12px',
                  zIndex: 10000,
                  marginTop: '4px',
                  WebkitAppRegion: 'no-drag'
                } as React.CSSProperties}
              >
                未找到相关消息
              </div>
            )}
          </div>
          <div style={{ flex: 1, overflowY: 'auto' }}>
            {contacts.map(contact => (
              <div
                key={contact.id}
                className={`contact-item ${contact.id === activeContactId ? 'active' : ''}`}
                onClick={() => {
                  setActiveContactId(contact.id)
                  unreadCountsRef.current[contact.id] = 0
                  setContacts(prev => prev.map(c => c.id === contact.id ? { ...c, unreadCount: 0 } : c))
                }}
                style={{
                  display: 'flex',
                  padding: '12px',
                  cursor: 'pointer',
                  backgroundColor: contact.id === activeContactId ? '#c6c6c6' : '#e6e6e6',
                  transition: 'background-color 0.2s',
                  borderBottom: '1px solid #d6d6d6'
                }}
              >
                <div style={{ position: 'relative', marginRight: '10px', flexShrink: 0 }}>
                  <div
                    style={{
                      width: '40px',
                      height: '40px',
                      borderRadius: '50%',
                      overflow: 'hidden',
                      flexShrink: 0
                    }}
                  >
                    {contact.avatar}
                  </div>
                  {contact.unreadCount > 0 && (
                    <div style={{
                      position: 'absolute', top: '-5px', right: '-5px',
                      backgroundColor: '#ff3b30', color: 'white',
                      borderRadius: '10px', padding: '0 5px', fontSize: '10px',
                      minWidth: '14px', height: '14px', lineHeight: '14px', textAlign: 'center'
                    }}>
                      {contact.unreadCount}
                    </div>
                  )}
                </div>
                <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                    <span style={{ fontWeight: '500', fontSize: '14px', color: '#000' }}>{contact.name}</span>
                    <span style={{ fontSize: '10px', color: '#999' }}>{contact.lastMessageTime}</span>
                  </div>
                  <div style={{ fontSize: '12px', color: '#888', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {contact.lastMessage}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </>
      )
    } 
    
    if (activeTab === 'contact') {
      return (
        <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
          {token ? (
            <div style={{ flex: 1, minHeight: 0 }}>
              <ContactList
                token={token}
                useAdminApi={false}
                onSelect={(contact: UserContact) => {
                  logger.info('App: Contact selected', { contactId: contact.id, contactName: contact.name })
                  setSelectedContactDetail(contact)
                }}
              />
            </div>
          ) : (
            <div style={{ padding: '20px', textAlign: 'center', color: '#999' }}>
              请先登录
            </div>
          )}
        </div>
      )
    }

    if (activeTab === 'browser') {
      return null
    }
    return null
  }

  if (isRestoringSession) {
    return (
      <div
        style={{
          minHeight: '100vh',
          width: '100%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: '#f5f5f5',
          color: '#666',
          fontSize: 15
        }}
      >
        正在登录中...
      </div>
    )
  }

  if (!isLoggedIn) {
    return <Login onLogin={handleLogin} bannerMessage={sessionExpiredMessage} />
  }

  return (
    <div className="app-container">
      <Navigation
        activeTab={activeTab}
        onTabChange={setActiveTab}
        onSettingsClick={() => setShowSettings(true)}
        currentUserId={currentUserId}
        currentUserName={currentUserName}
        totalUnread={totalUnread}
      />

      {activeTab !== 'browser' && (
        <div className="list-panel">
          {renderListPanel()}
        </div>
      )}

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', backgroundColor: '#f5f5f5' }}>
        {activeTab === 'chat' ? (
          isLoadingContacts ? (
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>
              加载联系人列表...
            </div>
          ) : (
            <ChatPage
              contacts={contacts}
              activeContact={activeContact}
              activeContactId={activeContactId}
              messages={messages}
              isLoadingMessages={isLoadingMessages}
              uploadProgress={uploadProgress}
              token={token}
              currentUserId={currentUserId}
              currentUserName={currentUserName}
              inputValue={inputValue}
              setInputValue={setInputValue}
              onSendMessage={handleSend}
              onFileSelect={handleFileSelect}
              onShowChatSearch={() => setShowChatSearchModal(true)}
              onContextMenu={handleContextMenu}
            />
          )
        ) : activeTab === 'browser' ? (
          token ? (
            <AppMappingList token={token} currentUserId={currentUserId} />
          ) : (
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>
              请先登录
            </div>
          )
        ) : activeTab === 'contact' ? (
          selectedContactDetail ? (
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', backgroundColor: '#f5f5f5' }}>
              <div style={{ padding: '0 20px', height: '60px', display: 'flex', alignItems: 'center', borderBottom: '1px solid #e7e7e7', justifyContent: 'space-between', WebkitAppRegion: 'drag', backgroundColor: '#fff' } as React.CSSProperties}>
                <div style={{ fontWeight: 'bold', fontSize: '16px', WebkitAppRegion: 'no-drag' } as React.CSSProperties}>
                  联系人详情
                </div>
              </div>
              
              <div style={{ flex: 1, overflowY: 'auto', padding: '40px 20px', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <div style={{ width: '100px', height: '100px', borderRadius: '50%', backgroundColor: 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '100px', marginBottom: '30px', border: '1px solid #e7e7e7', boxShadow: '0 2px 4px rgba(0,0,0,0.1)', overflow: 'hidden' }}>
                  {getDefaultAvatar(selectedContactDetail.id, selectedContactDetail.name || selectedContactDetail.english_name, { sizePx: 100 })}
                </div>
                
                <div style={{ fontSize: '20px', fontWeight: 'bold', marginBottom: '40px', color: '#333' }}>
                  {selectedContactDetail.name || selectedContactDetail.english_name || `用户${selectedContactDetail.id}`}
                </div>
                
                <div style={{ width: '100%', maxWidth: '500px', backgroundColor: '#fff', borderRadius: '8px', padding: '20px', boxShadow: '0 2px 4px rgba(0,0,0,0.05)' }}>
                  {selectedContactDetail.name && (
                    <div style={{ padding: '15px 0', borderBottom: '1px solid #f0f0f0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span style={{ color: '#999', fontSize: '14px' }}>中文名</span>
                      <span style={{ color: '#333', fontSize: '14px', fontWeight: '500' }}>{selectedContactDetail.name}</span>
                    </div>
                  )}
                  
                  {selectedContactDetail.english_name && (
                    <div style={{ padding: '15px 0', borderBottom: '1px solid #f0f0f0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span style={{ color: '#999', fontSize: '14px' }}>英文名</span>
                      <span style={{ color: '#333', fontSize: '14px', fontWeight: '500' }}>{selectedContactDetail.english_name}</span>
                    </div>
                  )}
                  
                  {selectedContactDetail.status && (
                    <div style={{ padding: '15px 0', borderBottom: '1px solid #f0f0f0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span style={{ color: '#999', fontSize: '14px' }}>状态</span>
                      <span style={{ color: '#333', fontSize: '14px', fontWeight: '500' }}>{selectedContactDetail.status}</span>
                    </div>
                  )}
                  
                  <div style={{ padding: '15px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span style={{ color: '#999', fontSize: '14px' }}>用户ID</span>
                    <span style={{ color: '#333', fontSize: '14px', fontWeight: '500' }}>{selectedContactDetail.id}</span>
                  </div>
                </div>
                
                <div style={{ marginTop: '50px', width: '100%', maxWidth: '500px', padding: '0 20px' }}>
                  <button
                    onClick={() => handleSendMessageFromContact(selectedContactDetail)}
                    style={{
                      width: '100%',
                      padding: '14px',
                      backgroundColor: '#1aad19',
                      color: 'white',
                      border: 'none',
                      borderRadius: '6px',
                      fontSize: '16px',
                      fontWeight: '500',
                      cursor: 'pointer',
                      transition: 'background-color 0.2s',
                      boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.backgroundColor = '#179b16'
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.backgroundColor = '#1aad19'
                    }}
                  >
                    发消息
                  </button>
                </div>
              </div>
            </div>
          ) : (
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#ccc', flexDirection: 'column' }}>
              <div style={{ fontSize: '80px', marginBottom: '20px', opacity: 0.2 }}>👥</div>
              <div>请从左侧选择联系人查看详情</div>
            </div>
          )
        ) : null}
      </div>

      {contextMenu && (
        <>
          <div 
            style={{ position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', zIndex: 999 }}
            onClick={() => setContextMenu(null)}
          />
          <div 
            className="context-menu" 
            style={{ top: contextMenu.y, left: contextMenu.x }}
          >
            <div className="context-menu-item" onClick={() => { alert('已复制'); setContextMenu(null) }}>复制</div>
            <div className="context-menu-item" onClick={() => { alert('已转发'); setContextMenu(null) }}>转发</div>
            <div className="context-menu-item" onClick={() => { alert('已收藏'); setContextMenu(null) }}>收藏</div>
            <div style={{ height: '1px', backgroundColor: '#eee', margin: '4px 0' }}></div>
            <div className="context-menu-item" onClick={() => { 
              if (activeContactId) {
                setMessages(prev => ({
                  ...prev,
                  [activeContactId]: (prev[activeContactId] || []).filter(m => m.id !== contextMenu.msgId)
                }))
              }
              setContextMenu(null)
            }}>删除</div>
            <div className="context-menu-item" onClick={() => { alert('撤回功能开发中'); setContextMenu(null) }}>撤回</div>
          </div>
        </>
      )}

      <SettingsModal
        isOpen={showSettings}
        onClose={() => setShowSettings(false)}
        currentUserId={currentUserId}
        currentUserName={currentUserName}
        onLogout={handleLogout}
      />

      {/* 历史搜索弹窗 - 简化版本，可以后续提取 */}
      {showChatSearchModal && (
        <div 
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: 'rgba(0,0,0,0.5)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            zIndex: 10000
          }} 
          onClick={(e) => {
            if (e.target === e.currentTarget) {
              setShowChatSearchModal(false)
              setChatSearchQuery('')
            }
          }}
        >
          <div 
            style={{
              backgroundColor: '#fff',
              borderRadius: '8px',
              padding: '20px',
              width: '600px',
              maxHeight: '80vh',
              display: 'flex',
              flexDirection: 'column',
              boxShadow: '0 4px 12px rgba(0,0,0,0.3)'
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <div style={{ 
              display: 'flex', 
              justifyContent: 'space-between', 
              alignItems: 'center',
              marginBottom: '20px',
              paddingBottom: '15px',
              borderBottom: '1px solid #e7e7e7'
            }}>
              <div style={{ fontSize: '18px', fontWeight: '500' }}>
                搜索与 {activeContact?.name} 的聊天记录
              </div>
              <span
                onClick={() => {
                  setShowChatSearchModal(false)
                  setChatSearchQuery('')
                }}
                style={{ 
                  cursor: 'pointer', 
                  fontSize: '20px', 
                  color: '#999',
                  lineHeight: '1'
                }}
              >
                ✕
              </span>
            </div>

            <div style={{ 
              backgroundColor: '#f0f0f0', 
              borderRadius: '4px', 
              padding: '10px 12px', 
              fontSize: '14px', 
              display: 'flex', 
              alignItems: 'center',
              marginBottom: '15px'
            }}>
              <BsSearch style={{ marginRight: '8px', fontSize: '16px', color: '#999' }} />
              <input
                type="text"
                placeholder="输入关键词搜索聊天记录..."
                value={chatSearchQuery}
                onChange={(e) => setChatSearchQuery(e.target.value)}
                autoFocus
                style={{
                  border: 'none',
                  outline: 'none',
                  backgroundColor: 'transparent',
                  flex: 1,
                  fontSize: '14px',
                  color: '#333'
                }}
              />
              {chatSearchQuery && (
                <span
                  onClick={() => setChatSearchQuery('')}
                  style={{ cursor: 'pointer', marginLeft: '8px', fontSize: '16px', color: '#999' }}
                >
                  ✕
                </span>
              )}
            </div>

            <div style={{ 
              flex: 1, 
              overflowY: 'auto',
              maxHeight: '400px'
            }}>
              {chatSearchQuery ? (
                chatSearchResults.length > 0 ? (
                  <div>
                    {chatSearchResults.map(msg => (
                      <div
                        key={msg.id}
                        onClick={(e) => {
                          e.preventDefault()
                          e.stopPropagation()
                          setShowChatSearchModal(false)
                          setChatSearchQuery('')
                          setTimeout(() => {
                            const messageElement = document.querySelector(`[data-message-id="${msg.id}"]`)
                            if (messageElement) {
                              messageElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
                              ;(messageElement as HTMLElement).style.backgroundColor = '#fff3cd'
                              setTimeout(() => {
                                ;(messageElement as HTMLElement).style.backgroundColor = ''
                              }, 2000)
                            }
                          }, 100)
                        }}
                        style={{
                          padding: '12px',
                          cursor: 'pointer',
                          borderBottom: '1px solid #f0f0f0',
                          fontSize: '14px',
                          transition: 'background-color 0.2s'
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.backgroundColor = '#f5f5f5'
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.backgroundColor = '#fff'
                        }}
                      >
                        <div style={{ 
                          display: 'flex', 
                          justifyContent: 'space-between', 
                          alignItems: 'center',
                          marginBottom: '6px'
                        }}>
                          <div style={{ color: '#999', fontSize: '12px' }}>
                            {formatFullDateTime(msg.timestamp)}
                          </div>
                          {msg.isSelf && (
                            <div style={{ 
                              color: '#07c160', 
                              fontSize: '11px',
                              backgroundColor: '#e8f5e9',
                              padding: '2px 6px',
                              borderRadius: '2px'
                            }}>
                              我
                            </div>
                          )}
                        </div>
                        <div style={{ 
                          color: '#333',
                          lineHeight: '1.5',
                          wordBreak: 'break-word'
                        }}>
                          {msg.type === 'text' ? msg.content : `[${msg.type === 'image' ? '图片' : msg.type === 'file' ? '文件' : msg.type === 'video' ? '视频' : '通知'}] ${msg.title || ''}`}
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div style={{ 
                    padding: '40px',
                    textAlign: 'center',
                    color: '#999',
                    fontSize: '14px'
                  }}>
                    未找到相关消息
                  </div>
                )
              ) : (
                <div style={{ 
                  padding: '40px',
                  textAlign: 'center',
                  color: '#999',
                  fontSize: '14px'
                }}>
                  请输入关键词搜索聊天记录
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default App
