import ChatSidebarItem from './ChatSidebarItem';
import { IconButton } from '@/components/ui/button';
import ChatSidebarAction from './ChatSidebarAction';
import ChatSearchResults from './ChatSearchResults';
import { Input } from '@/components/ui/input';
import { useState, useEffect, useCallback } from 'react';
import { useStreamChatStore } from '@/stores/stream-chat';
import { useLayoutStore } from '@/stores';

const ChatSidebar = () => {
  const isSidebarExpanded = useLayoutStore((s) => s.isSidebarExpanded);
  const currentChannel = useStreamChatStore((state) => state.currentChannel);
  const channels = useStreamChatStore((state) => state.channels);
  const [search, setSearch] = useState('');
  const [inSearching, setIsSearching] = useState(false);

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

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

  const handleCloseSearch = useCallback(() => {
    setSearch('');
    setIsSearching(false);
  }, []);

  // 如果有搜索关键词，显示搜索结果
  const isShowingSearchResults = search.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">
          {isSidebarExpanded ? (
            <>
              <span className="txt-label-s text-txt-secondary-normal">Chats</span>
              <ChatSidebarAction
                onSearchClick={() => setIsSearching(true)}
                onCancelSearch={handleCloseSearch}
                isSearchActive={inSearching}
              />
            </>
          ) : (
            <span className="txt-label-s text-txt-secondary-normal w-full text-center">Chats</span>
          )}
        </div>

        {/* 搜索框 - 根据设计稿实现 */}
        {inSearching && isSidebarExpanded && (
          <div className="relative mb-2 flex items-center gap-1 px-2 py-1">
            <div className="relative flex-1">
              <Input
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                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={() => setSearch('')}
                  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>
        )}

        {/* 根据搜索状态显示不同内容 */}
        {inSearching ? (
          isShowingSearchResults ? (
            <ChatSearchResults
              searchKeyword={search}
              isExpanded={isSidebarExpanded}
              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={isSidebarExpanded}
                      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;
