'use client';
import { useState, useMemo } from 'react';
import ChatSidebarItem from './ChatSidebarItem';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import Empty from '@/components/ui/empty';
import { useStreamChatStore } from '@/app/(main)/chat/[id]/stream-chat';

interface ChatSearchResultsProps {
  searchKeyword: string;
  isExpanded: boolean;
}

const ChatSearchResults = ({ searchKeyword, isExpanded }: ChatSearchResultsProps) => {
  const channels = useStreamChatStore((state) => state.channels);
  const [activeTab, setActiveTab] = useState('message');

  // 筛选Message搜索结果 - 对用户名或最后一条消息内容进行搜索
  const { nameRes, messageRes } = useMemo(() => {
    const nameRes: any[] = [];
    const messageRes: any[] = [];
    if (!searchKeyword) {
      return {
        nameRes,
        messageRes,
      };
    }

    channels.forEach((chanel) => {
      const { name } = (chanel?.data as any) ?? {};
      const keyword = searchKeyword.toLowerCase();

      // 搜索用户名
      if (name?.toLowerCase().includes(keyword)) {
        nameRes.push(chanel);
      }
      const messages = chanel?.state?.messages || [];
      const lastMessage = messages[messages.length - 1];
      // 搜索最后一条消息内容
      if (lastMessage?.text?.toLowerCase().includes(keyword)) {
        messageRes.push(chanel);
      }
    });

    return {
      nameRes,
      messageRes,
    };
  }, [channels, searchKeyword]);

  if (!searchKeyword) {
    return <div className="flex-1" />;
  }

  return (
    <div className="flex min-h-0 flex-1 flex-col">
      <Tabs value={activeTab} onValueChange={setActiveTab} className="flex flex-1 flex-col">
        {/* Tab 切换 */}
        <TabsList className="mb-0 h-auto w-fit justify-start gap-4 bg-transparent p-0">
          <TabsTrigger value="message" className="relative h-auto flex-col gap-1">
            <span className="txt-title-s text-txt-secondary-normal group-data-[state=active]:text-txt-primary-normal">
              Person
            </span>
            <div className="bg-primary-normal h-1 w-5 rounded opacity-0 group-data-[state=active]:opacity-100" />
          </TabsTrigger>
          <TabsTrigger value="person" className="relative h-auto flex-col gap-1">
            <span className="txt-title-s text-txt-secondary-normal group-data-[state=active]:text-txt-primary-normal">
              Message
            </span>
            <div className="bg-primary-normal h-1 w-5 rounded opacity-0 group-data-[state=active]:opacity-100" />
          </TabsTrigger>
        </TabsList>

        <TabsContent value="message" className="mt-0 flex-1 space-y-1 overflow-y-auto">
          {nameRes.length > 0 ? (
            nameRes.map((chanel: any) => (
              <ChatSidebarItem
                key={chanel.id}
                chanel={chanel}
                isExpanded={isExpanded}
                isSelected={false}
                searchKeyword={searchKeyword}
              />
            ))
          ) : (
            <div className="text-txt-secondary-normal flex items-center justify-center py-16">
              <Empty title="Nothing here… :3" />
            </div>
          )}
        </TabsContent>

        <TabsContent value="person" className="mt-0 flex-1 overflow-y-auto">
          {messageRes.length > 0 ? (
            messageRes.map((chanel: any) => (
              <ChatSidebarItem
                key={chanel.id}
                chanel={chanel}
                isExpanded={isExpanded}
                isSelected={false}
                searchKeyword={searchKeyword}
              />
            ))
          ) : (
            <div className="text-txt-secondary-normal flex items-center justify-center py-16">
              <Empty title="Nothing here… :3" />
            </div>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
};

export default ChatSearchResults;
