import { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { Text, View } from '@tarojs/components'
import CustomNavBar from '@/components/layout/CustomNavBar'
import PageShell from '@/components/layout/PageShell'
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 { useTabRefresh } from '@/hooks/useTabRefresh'
import { markFresh } from '@/store/dataBus'
import { ensureProfileReady } from '@/store/session.store'
import type { TabViewProps } from '@/components/navigation/BottomTabBar/tabConfig'
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({ active = false, showTick = 0 }: TabViewProps) {
  const [tab, setTab] = useState<MessageTab>('all')
  const [activeUsers, setActiveUsers] = useState<ActiveUser[]>([])
  const [conversations, setConversations] = useState<Conversation[]>([])
  const [keyword, setKeyword] = useState('')

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

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

  // Refresh unread counts / new conversations when coming back from a chat —
  // only when something changed (a message was sent/read) or the TTL elapsed.
  useTabRefresh('messages', active, showTick, load)

  const setConversationUnread = (conversationId: string, unreadCount: number) => {
    setConversations(current =>
      current.map(c => (c._id === conversationId ? { ...c, unreadCount } : c))
    )
  }

  const openConversation = async (item: Conversation) => {
    if (!(await ensureProfileReady())) return
    const previousUnread = item.unreadCount

    if (item.type === 'system') {
      if (previousUnread <= 0) {
        Taro.showToast({ title: '系统消息暂不支持聊天', icon: 'none' })
        return
      }

      setConversationUnread(item._id, 0)
      try {
        await markConversationRead(item._id)
        Taro.showToast({ title: '系统消息已读', icon: 'success' })
      } catch {
        setConversationUnread(item._id, previousUnread)
        Taro.showToast({ title: '操作失败，请重试', icon: 'none' })
      }
      return
    }

    if (previousUnread > 0) setConversationUnread(item._id, 0)

    try {
      await Taro.navigateTo({
        url: `/pages/chat/index?conversationId=${item._id}&title=${encodeURIComponent(item.title)}`
      })
    } catch {
      if (previousUnread > 0) setConversationUnread(item._id, previousUnread)
      Taro.showToast({ title: '打开聊天失败，请重试', icon: 'none' })
      return
    }

    if (previousUnread <= 0) return

    try {
      await markConversationRead(item._id)
    } catch {
      setConversationUnread(item._id, previousUnread)
    }
  }

  const openChatWith = async (user: ActiveUser) => {
    if (!(await ensureProfileReady())) return
    try {
      await Taro.navigateTo({
        url: `/pages/chat/index?targetUserId=${user.id}&title=${encodeURIComponent(user.name)}`
      })
    } catch {
      Taro.showToast({ title: '打开聊天失败，请重试', icon: 'none' })
    }
  }

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

  const kw = keyword.trim().toLowerCase()
  const visibleActiveUsers = kw
    ? activeUsers.filter(user => user.name.toLowerCase().includes(kw))
    : activeUsers
  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 ? (
        visibleActiveUsers.length > 0 ? (
          <>
            <View className='messages-page__divider'>
              <Text>在线汪友</Text>
            </View>
            <ActiveUserRow users={visibleActiveUsers} onSelect={openChatWith} showDiscover={false} />
          </>
        ) : null
      ) : (
        <ActiveUserRow users={activeUsers} onSelect={openChatWith} onDiscover={goContacts} />
      )}
      <View className='messages-page__divider'>
        <Text>{kw && visibleActiveUsers.length > 0 ? '匹配聊天' : 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
              ? visibleActiveUsers.length > 0
                ? '没有匹配的聊天'
                : '没有匹配的汪友或聊天'
              : tab === 'unread'
                ? '没有未读消息'
                : '还没有聊天，去「附近」加汪友吧'}
          </Text>
        ) : null}
      </View>
    </PageShell>
  )
}
