import ChatSidebarItem from './ChatSidebarItem'
import { IconButton } from '@/components/ui/button'
import { useAtomValue } from 'jotai'
import { conversationListAtom, selectedConversationIdAtom } from '@/atoms/im'
import ChatSidebarAction from './ChatSidebarAction'
import ChatSearchResults from './ChatSearchResults'
import { Input } from '@/components/ui/input'
import { useState, useEffect, useCallback } from 'react'

const ChatSidebar = ({ isExpanded }: { isExpanded: boolean }) => {
  const selectedChat = useAtomValue(selectedConversationIdAtom)
  const conversationList = useAtomValue(conversationListAtom)
  const [searchKeyword, setSearchKeyword] = useState('')
  const [showSearchInput, setShowSearchInput] = useState(false)

  const datas = Array.from(conversationList.values()).sort((a, b) => {
    // 获取会话的最后活跃时间（优先使用最后一条消息的时间，否则使用会话更新时间）
    const aTime = a.lastMessage?.messageRefer?.createTime || a.updateTime || 0
    const bTime = b.lastMessage?.messageRefer?.createTime || b.updateTime || 0
    // 按时间倒序排列（最新的在前面）
    return bTime - aTime
  })

  // 当侧边栏收缩时，取消搜索功能
  useEffect(() => {
    if (!isExpanded) {
      setShowSearchInput(false)
      setSearchKeyword('')
    }
  }, [isExpanded])

  const handleSearchClick = () => {
    setShowSearchInput(true)
  }

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchKeyword(e.target.value)
  }

  const handleClearSearch = () => {
    setSearchKeyword('')
  }

  const handleCloseSearch = useCallback(() => {
    setSearchKeyword('')
    setShowSearchInput(false)
  }, [])

  // ESC键关闭搜索
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape' && showSearchInput) {
        handleCloseSearch()
      }
    }

    if (showSearchInput) {
      document.addEventListener('keydown', handleKeyDown)
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown)
    }
  }, [showSearchInput, handleCloseSearch])

  // 如果有搜索关键词，显示搜索结果
  const isShowingSearchResults = searchKeyword.trim().length > 0

  if (!datas.length && !isShowingSearchResults) {
    return <div className="flex-1"></div>
  }

  return (
    <>
      {/* 分割线 */}
      <div className="mx-6 my-4">
        <div className="bg-outline-normal h-px" />
      </div>
      <div className="flex min-h-0 flex-1 flex-col px-4">
        {/* 聊天标题 */}
        <div className="mb-2 flex h-10 items-center justify-between px-2 py-1">
          {isExpanded ? (
            <>
              <span className="txt-label-s text-txt-secondary-normal">Chats</span>
              <ChatSidebarAction
                onSearchClick={handleSearchClick}
                onCancelSearch={handleCloseSearch}
                isSearchActive={showSearchInput}
              />
            </>
          ) : (
            <span className="txt-label-s text-txt-secondary-normal w-full text-center">Chats</span>
          )}
        </div>

        {/* 搜索框 - 根据设计稿实现 */}
        {showSearchInput && isExpanded && (
          <div className="relative mb-2 flex items-center gap-1 px-2 py-1">
            <div className="relative flex-1">
              <Input
                type="text"
                value={searchKeyword}
                onChange={handleSearchChange}
                placeholder="Search"
                size="small"
                autoFocus
                maxLength={50}
                prefixIcon={
                  <i className="iconfont icon-Search text-txt-secondary-normal text-sm" />
                }
                className="rounded-full"
              />
              {isShowingSearchResults && (
                <IconButton
                  onClick={handleClearSearch}
                  size="mini"
                  variant="tertiary"
                  className="absolute top-1/2 right-3 shrink-0 -translate-y-1/2 transform"
                >
                  <i className="iconfont icon-close" />
                </IconButton>
              )}
            </div>
            <IconButton
              onClick={handleCloseSearch}
              variant="ghost"
              size="small"
              className="shrink-0"
            >
              <i className="iconfont icon-close" />
            </IconButton>
          </div>
        )}

        {/* 根据搜索状态显示不同内容 */}
        {showSearchInput ? (
          isShowingSearchResults ? (
            <ChatSearchResults
              searchKeyword={searchKeyword}
              isExpanded={isExpanded}
              onCloseSearch={handleCloseSearch}
            />
          ) : (
            <div className="flex-1" />
          )
        ) : (
          <>
            {/* 聊天项列表 */}
            <div className="relative min-h-0 flex-1">
              <div className="relative h-full">
                <div className="h-full space-y-2 overflow-x-hidden overflow-y-auto py-2">
                  {datas.map((chat) => (
                    <ChatSidebarItem
                      key={chat.conversationId}
                      conversation={chat}
                      isExpanded={isExpanded}
                      isSelected={selectedChat === chat.conversationId}
                    />
                  ))}
                </div>
                {/* 底部渐变遮罩 */}
                <div
                  className="pointer-events-none absolute right-0 bottom-0 left-0 h-4"
                  style={{
                    background: 'linear-gradient(180deg, rgba(33, 26, 43, 0) 0%, #211A2B 100%)',
                  }}
                />
              </div>
            </div>
          </>
        )}
      </div>
    </>
  )
}

export default ChatSidebar
