'use client'
import { useState, useMemo, useEffect } from 'react'
import { useAtomValue } from 'jotai'
import { conversationListAtom } from '@/atoms/im'
import { useInfiniteQuery } from '@tanstack/react-query'
import { imService } from '@/services/im'
import { imKeys } from '@/lib/query-keys'
import ChatSidebarItem from './ChatSidebarItem'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { InfiniteScrollList } from '@/components/ui/infinite-scroll-list'
import { getAge } from '@/lib/utils'
import { useRouter } from 'next/navigation'
import { HeartbeatRelationListOutput } from '@/services/im/types'
import Empty from '@/components/ui/empty'
import AIRelationTag from '@/components/features/AIRelationTag'
import Image from 'next/image'
import { IconButton } from '@/components/ui/button'
import { usePrefetchRoutes } from '@/hooks/useGlobalPrefetchRoutes'

interface ChatSearchResultsProps {
  searchKeyword: string
  isExpanded: boolean
  onCloseSearch: () => void
}

// 高亮搜索关键词的组件
const HighlightText = ({ text, keyword }: { text: string; keyword: string }) => {
  if (!keyword) return <span>{text}</span>

  const parts = text.split(new RegExp(`(${keyword})`, 'gi'))
  return (
    <span>
      {parts.map((part, index) =>
        part.toLowerCase() === keyword.toLowerCase() ? (
          <span key={index} className="text-primary-variant-normal">
            {part}
          </span>
        ) : (
          <span key={index}>{part}</span>
        )
      )}
    </span>
  )
}

// Person Tab中的关系列表项组件
const PersonItem = ({
  person,
  keyword,
  onCloseSearch,
}: {
  person: HeartbeatRelationListOutput
  keyword: string
  onCloseSearch: () => void
}) => {
  const router = useRouter()
  const chatHref = useMemo(() => (person.aiId ? `/chat/${person.aiId}` : null), [person.aiId])
  usePrefetchRoutes(chatHref ? [chatHref] : undefined)

  const handleClick = () => {
    if (chatHref) {
      router.push(chatHref)
      onCloseSearch()
    }
  }

  return (
    <div
      className="hover:bg-surface-element-normal flex cursor-pointer items-center gap-3 rounded-lg p-3 transition-colors"
      onClick={handleClick}
    >
      {/* 头像 */}
      <div className="relative shrink-0">
        <Avatar className="size-12">
          <AvatarImage src={person.headImg} alt={person.nickname} />
          <AvatarFallback className="bg-surface-element-normal text-txt-primary-normal txt-label-m">
            {(person.nickname || '').charAt(0)}
          </AvatarFallback>
        </Avatar>
        {/* 心动等级显示 */}
      </div>

      {/* 用户信息 */}
      <div className="min-w-0 flex-1">
        <div className="mb-1 flex items-center gap-2">
          <span className="txt-label-m text-txt-primary-normal truncate font-medium">
            <HighlightText text={person.nickname || ''} keyword={keyword} />
          </span>
          {person.heartbeatLevel && person.isShow && (
            <AIRelationTag heartbeatLevel={person.heartbeatLevel} size="mini" />
          )}
        </div>

        {/* 心动值和角色信息 */}
        <div className="txt-body-s text-txt-secondary-normal flex items-center gap-2">
          {/* 心动值 */}
          {person.heartbeatVal !== undefined && (
            <>
              <div className="flex items-center gap-1">
                <Image src="/icons/heart.svg" alt="Heart" width={12} height={12} />
                <span className="txt-label-s">{person.heartbeatVal}℃</span>
              </div>

              {/* 分隔线 */}
              {person.characterName && <div className="border-outline-normal h-3 w-0 border-l" />}
            </>
          )}

          {/* 角色信息 */}
          {person.characterName && (
            <span className="min-w-0 flex-1 truncate">
              {[getAge(person.birthday as unknown as number), person.characterName, person.tagName]
                .filter(Boolean)
                .join(' · ')}
            </span>
          )}
        </div>
      </div>

      <IconButton iconfont="icon-Chat" size="small" />
    </div>
  )
}

// Person列表加载骨架屏组件
const PersonSkeleton = () => (
  <div className="flex animate-pulse items-center gap-3 p-3">
    <div className="bg-surface-nest-normal size-12 shrink-0 rounded-full" />
    <div className="min-w-0 flex-1">
      <div className="mb-2 flex items-center gap-2">
        <div className="bg-surface-nest-normal h-4 w-24 rounded" />
        <div className="bg-surface-nest-normal h-4 w-12 rounded" />
      </div>
      <div className="flex items-center gap-2">
        <div className="flex items-center gap-1">
          <div className="bg-surface-nest-normal h-3 w-3 rounded" />
          <div className="bg-surface-nest-normal h-3 w-8 rounded" />
        </div>
        <div className="h-3 w-0 border-l border-gray-600" />
        <div className="bg-surface-nest-normal h-3 w-16 rounded" />
      </div>
    </div>
  </div>
)

// Person空状态组件
const PersonEmptyState = () => (
  <div className="text-txt-secondary-normal flex items-center justify-center py-16">
    <Empty title="Nothing here… :3" />
  </div>
)

const ChatSearchResults = ({
  searchKeyword,
  isExpanded,
  onCloseSearch,
}: ChatSearchResultsProps) => {
  const conversationList = useAtomValue(conversationListAtom)
  const [activeTab, setActiveTab] = useState('message')
  const [debouncedSearchKeyword, setDebouncedSearchKeyword] = useState(searchKeyword)

  // 防抖处理搜索关键词，避免频繁调用API
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearchKeyword(searchKeyword)
    }, 500) // 500ms防抖延迟

    return () => clearTimeout(timer)
  }, [searchKeyword])

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

    const conversations = Array.from(conversationList.values())
    return conversations.filter((conversation) => {
      const { name } = conversation
      const keyword = searchKeyword.toLowerCase()

      // 搜索用户名
      if (name?.toLowerCase().includes(keyword)) {
        return true
      }

      // // 搜索最后一条消息内容
      // if (lastMessage?.text?.toLowerCase().includes(keyword)) {
      //   return true;
      // }

      return false
    })
  }, [conversationList, searchKeyword])

  // 使用无限查询获取Person搜索结果
  const {
    data: personData,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    isLoading: isPersonLoading,
  } = useInfiniteQuery({
    queryKey: [...imKeys.heartbeatRelationList(debouncedSearchKeyword), 'infinite'],
    queryFn: ({ pageParam = 1 }) =>
      imService.getHeartbeatRelationList({
        nickname: debouncedSearchKeyword,
        page: { pn: pageParam, ps: 20 },
      }),
    initialPageParam: 1,
    getNextPageParam: (lastPage, allPages) => {
      const currentPage = allPages.length
      const totalPages = Math.ceil((lastPage.tc || 0) / 20)
      return currentPage < totalPages ? currentPage + 1 : undefined
    },
    enabled: !!debouncedSearchKeyword && activeTab === 'person',
  })

  const personResults = personData?.pages.flatMap((page) => page.datas || []) || []

  // 判断是否正在等待防抖
  const isWaitingForDebounce = searchKeyword !== debouncedSearchKeyword

  // 如果没有搜索关键词，返回空状态
  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">
              Chats
            </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">
              My Crushes
            </span>
            <div className="bg-primary-normal h-1 w-5 rounded opacity-0 group-data-[state=active]:opacity-100" />
          </TabsTrigger>
        </TabsList>

        {/* Message Tab 内容 */}
        <TabsContent value="message" className="mt-0 flex-1 space-y-1 overflow-y-auto">
          {messageResults.length > 0 ? (
            messageResults.map((conversation) => (
              <ChatSidebarItem
                key={conversation.conversationId}
                conversation={conversation}
                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>

        {/* Person Tab 内容 */}
        <TabsContent value="person" className="mt-0 flex-1 overflow-y-auto">
          {isPersonLoading || isWaitingForDebounce ? (
            <div className="space-y-1">
              {Array.from({ length: 6 }).map((_, index) => (
                <PersonSkeleton key={index} />
              ))}
            </div>
          ) : (
            <InfiniteScrollList<HeartbeatRelationListOutput>
              items={personResults}
              renderItem={(person) => (
                <PersonItem person={person} keyword={searchKeyword} onCloseSearch={onCloseSearch} />
              )}
              getItemKey={(person) => person.aiId?.toString() || 'unknown'}
              hasNextPage={!!hasNextPage}
              isLoading={isPersonLoading || isFetchingNextPage}
              fetchNextPage={fetchNextPage}
              columns={1}
              gap={1}
              className="!grid-cols-1 space-y-1" // 强制单列布局
              LoadingSkeleton={PersonSkeleton}
              EmptyComponent={PersonEmptyState}
              hasError={false}
              enabled={!!debouncedSearchKeyword}
            />
          )}
        </TabsContent>
      </Tabs>
    </div>
  )
}

export default ChatSearchResults
