import { useEffect, useRef, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { Text, View } from '@tarojs/components'
import CustomNavBar from '@/components/layout/CustomNavBar'
import PageShell from '@/components/layout/PageShell'
import BottomTabBar from '@/components/navigation/BottomTabBar'
import SearchBar from '@/components/ui/SearchBar'
import SegmentedTabs from '@/components/ui/SegmentedTabs'
import ActiveUserRow from '@/features/messages/components/ActiveUserRow'
import ConversationItem from '@/features/messages/components/ConversationItem'
import { getMessages, markConversationRead } from '@/services/message.service'
import type { ActiveUser, Conversation, MessageTab } from '@/types/domain'
import './index.scss'

const tabs = [
  { key: 'all', label: '全部' },
  { key: 'unread', label: '未读' }
] as const

export default function MessagesPage() {
  const [tab, setTab] = useState<MessageTab>('all')
  const [activeUsers, setActiveUsers] = useState<ActiveUser[]>([])
  const [conversations, setConversations] = useState<Conversation[]>([])
  const [keyword, setKeyword] = useState('')
  const firstShow = useRef(true)

  const load = () => {
    getMessages(tab).then(result => {
      setActiveUsers(result.activeUsers)
      setConversations(result.conversations)
    })
  }

  useEffect(() => {
    load()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tab])

  // Refresh unread counts / new conversations when coming back from a chat.
  useDidShow(() => {
    if (firstShow.current) {
      firstShow.current = false
      return
    }
    load()
  })

  const openConversation = async (item: Conversation) => {
    setConversations(current => current.map(c => (c._id === item._id ? { ...c, unreadCount: 0 } : c)))
    markConversationRead(item._id)
    Taro.navigateTo({
      url: `/pages/chat/index?conversationId=${item._id}&title=${encodeURIComponent(item.title)}`
    })
  }

  const openChatWith = (user: ActiveUser) => {
    Taro.navigateTo({
      url: `/pages/chat/index?targetUserId=${user.id}&title=${encodeURIComponent(user.name)}`
    })
  }

  const goContacts = () => Taro.navigateTo({ url: '/pages/contacts/index' })

  const kw = keyword.trim().toLowerCase()
  const visibleConversations = kw
    ? conversations.filter(
        c => c.title.toLowerCase().includes(kw) || (c.preview || '').toLowerCase().includes(kw)
      )
    : conversations

  return (
    <PageShell className='messages-page'>
      <CustomNavBar title='消息' />
      <SearchBar placeholder='搜索聊天或通知' value={keyword} onInput={setKeyword} />
      <SegmentedTabs items={tabs as any} value={tab} onChange={setTab} />
      {kw ? null : <ActiveUserRow users={activeUsers} onSelect={openChatWith} onDiscover={goContacts} />}
      <View className='messages-page__divider'>
        <Text>{kw ? '搜索结果' : '最近聊天'}</Text>
      </View>
      <View className='messages-page__list'>
        {visibleConversations.map(item => (
          <ConversationItem key={item._id} conversation={item} onClick={() => openConversation(item)} />
        ))}
        {visibleConversations.length === 0 ? (
          <Text className='messages-page__empty'>
            {kw
              ? '没有匹配的聊天'
              : tab === 'unread'
                ? '没有未读消息'
                : '还没有聊天，去「发现」找汪友聊聊吧'}
          </Text>
        ) : null}
      </View>
      <BottomTabBar active='messages' />
    </PageShell>
  )
}
