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 '@/app/(main)/chat/[id]/stream-chat';
import { useLayoutStore } from '@/stores';
import { useParams } from 'next/navigation';
import { useTranslations } from 'next-intl';

const ChatSidebar = ({
  expand,
  showSeparator = false,
}: {
  expand?: boolean;
  showSeparator?: boolean;
}) => {
  const isSidebarExpanded = useLayoutStore((s) => s.isSidebarExpanded);
  const { id } = useParams<{ id: string }>();
  const t = useTranslations('chat');
  const channels = useStreamChatStore((state) => state.channels);
  const [search, setSearch] = useState('');
  const [inSearching, setIsSearching] = useState(false);

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

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

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

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

  const finalExpand = expand || isSidebarExpanded;

  return (
    <>
      {/* 分割线 */}
      {showSeparator && channels.length > 0 && (
        <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">
          <span className="txt-label-s text-txt-secondary-normal">{t('chats')}</span>
          {finalExpand && (
            <ChatSidebarAction
              onSearchClick={() => setIsSearching(true)}
              onCancelSearch={handleCloseSearch}
              isSearchActive={inSearching}
            />
          )}
        </div>

        {/* 搜索框 - 根据设计稿实现 */}
        {inSearching && finalExpand && (
          <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={finalExpand} />
          ) : (
            <div className="flex-1" />
          )
        ) : (
          <div className="relative min-h-0 flex-1">
            <div className="h-full max-w-full space-y-2 overflow-x-hidden overflow-y-auto py-2">
              {channels.map((chat) => (
                <ChatSidebarItem
                  key={chat.id}
                  chanel={chat}
                  isExpanded={finalExpand}
                  isSelected={id === chat.id}
                />
              ))}
            </div>
          </div>
        )}
      </div>
    </>
  );
};

export default ChatSidebar;
