import { useEffect, useRef, useState } from 'react'
import Taro, { useRouter, useDidShow, useDidHide } from '@tarojs/taro'
import { Image, Input, ScrollView, Text, View } from '@tarojs/components'
import { useSystemLayout } from '@/hooks/useSystemLayout'
import Icon from '@/components/ui/Icon'
import Avatar from '@/components/ui/Avatar'
import { getThread, sendMessage } from '@/services/message.service'
import type { ChatMessage, ChatPeer } from '@/types/domain'
import './index.scss'

export default function ChatPage() {
  const { statusBarHeight, safeBottom } = useSystemLayout()
  const router = useRouter()
  const initialConvId = router.params.conversationId || ''
  const targetUserId = router.params.targetUserId || ''
  const initialTitle = decodeURIComponent(router.params.title || '聊天')

  const [conversationId, setConversationId] = useState(initialConvId)
  const [peer, setPeer] = useState<ChatPeer | null>(null)
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [draft, setDraft] = useState('')
  const [sending, setSending] = useState(false)
  const [scrollTop, setScrollTop] = useState(0)
  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)

  const load = async () => {
    const res = await getThread({
      conversationId: conversationId || undefined,
      targetUserId: conversationId ? undefined : targetUserId || undefined
    })
    if (res.conversationId && res.conversationId !== conversationId) setConversationId(res.conversationId)
    if (res.peer) setPeer(res.peer)
    setMessages(res.messages)
    setScrollTop(prev => prev + 100000)
  }

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

  // Light polling for new messages while the page is visible.
  useDidShow(() => {
    pollRef.current = setInterval(load, 5000)
  })
  useDidHide(() => {
    if (pollRef.current) clearInterval(pollRef.current)
  })
  useEffect(() => () => {
    if (pollRef.current) clearInterval(pollRef.current)
  }, [])

  const send = async () => {
    const text = draft.trim()
    if (!text || sending) return
    setSending(true)
    setDraft('')
    try {
      const res = await sendMessage(text, {
        conversationId: conversationId || undefined,
        toUserId: conversationId ? undefined : targetUserId || undefined
      })
      if (res.conversationId) setConversationId(res.conversationId)
      await load()
    } catch {
      Taro.showToast({ title: '发送失败', icon: 'none' })
      setDraft(text)
    } finally {
      setSending(false)
    }
  }

  const title = peer?.name || initialTitle

  return (
    <View className='chat'>
      <View className='chat__nav' style={{ paddingTop: `${statusBarHeight}px` }}>
        <View className='chat__nav-row'>
          <View className='chat__back' onClick={() => Taro.navigateBack()}>
            <Icon name='chev' size={22} className='chat__back-icon' />
          </View>
          <Text className='chat__title'>{title}</Text>
          <View className='chat__nav-spacer' />
        </View>
      </View>

      <ScrollView scrollY className='chat__scroll' scrollTop={scrollTop} scrollWithAnimation enhanced showScrollbar={false}>
        <View className='chat__list'>
          {messages.length === 0 ? (
            <Text className='chat__empty'>还没有消息，打个招呼吧 👋</Text>
          ) : (
            messages.map(m => (
              <View key={m._id} className={`chat__row ${m.fromMe ? 'chat__row--me' : ''}`}>
                {!m.fromMe ? (
                  <Avatar avatarKey={peer?.avatarKey} avatarUrl={peer?.avatarUrl} size='sm' />
                ) : null}
                <View className='chat__bubble-wrap'>
                  <View className={`chat__bubble ${m.fromMe ? 'chat__bubble--me' : ''}`}>{m.content}</View>
                  <Text className='chat__time'>{m.timeText}</Text>
                </View>
              </View>
            ))
          )}
        </View>
      </ScrollView>

      <View className='chat__input-bar' style={{ paddingBottom: `${Math.max(12, safeBottom)}px` }}>
        <Input
          className='chat__input'
          value={draft}
          placeholder='发消息…'
          placeholderClass='chat__input-ph'
          confirmType='send'
          onInput={e => setDraft(e.detail.value)}
          onConfirm={send}
        />
        <View className={`chat__send ${draft.trim() ? '' : 'chat__send--disabled'}`} onClick={send}>
          发送
        </View>
      </View>
    </View>
  )
}
