import { View, Text, ScrollView } from '@tarojs/components'
import { useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { getToken } from '@/services/auth'
import { getConversations, ChatConversation } from '../../services/chat'
import './index.scss'

export default function Chat() {
  const [conversations, setConversations] = useState<ChatConversation[]>([])
  const [loading, setLoading] = useState(true)

  useDidShow(() => {
    void loadConversations()
  })

  const loadConversations = async () => {
    if (!getToken()) {
      Taro.reLaunch({ url: '/pages/login/index' })
      return
    }

    setLoading(true)
    try {
      const data = await getConversations()
      setConversations(data)
    } catch (error: any) {
      console.error('[chat] load failed:', error)
      Taro.showToast({
        title: error?.message || '加载失败，请稍后重试',
        icon: 'none',
      })
    } finally {
      setLoading(false)
    }
  }

  const handleConversationClick = (conversation: ChatConversation) => {
    Taro.navigateTo({
      url:
        `/pages/chat/detail/index?id=${conversation.id}` +
        `&source=${conversation.source}` +
        `&name=${encodeURIComponent(conversation.name)}` +
        `&peerKind=${conversation.peerKind}` +
        `&roleKey=${encodeURIComponent(conversation.roleKey || '')}` +
        `&conversationTypeName=${encodeURIComponent(conversation.conversationTypeName || '')}` +
        `&peerId=${encodeURIComponent(conversation.peerId || '')}` +
        `&childId=${conversation.childId || ''}` +
        `&childName=${encodeURIComponent(conversation.childName || '')}` +
        `&parentUserId=${conversation.parentUserId || ''}` +
        `&deviceId=${encodeURIComponent(conversation.deviceId || '')}` +
        `&channelLabel=${encodeURIComponent(conversation.channelLabel || '')}` +
        `&canSend=${conversation.canSend ? '1' : '0'}`,
    })
  }

  return (
    <View className='chat-page'>
      <View className='page-header'>
        <Text className='page-title'>玩伴</Text>
      </View>

      {loading ? (
        <View className='loading'>
          <Text>加载中...</Text>
        </View>
      ) : conversations.length === 0 ? (
        <View className='empty-card'>
          <Text className='empty-title'>暂无玩伴会话</Text>
        </View>
      ) : (
        <ScrollView className='conversation-list' scrollY>
          {conversations.map((conversation) => (
            <View
              key={conversation.key}
              className='conversation-item'
              onClick={() => handleConversationClick(conversation)}
            >
              <View className='conversation-avatar'>
                <Text className='avatar-icon'>{conversation.avatar}</Text>
              </View>
              <View className='conversation-content'>
                <View className='conversation-header'>
                  <View className='conversation-name-wrap'>
                    <Text className='conversation-name'>{conversation.name}</Text>
                    <Text className={`conversation-tag ${conversation.peerKind}`}>{conversation.typeLabel}</Text>
                  </View>
                  <Text className='conversation-time'>{conversation.time}</Text>
                </View>
                <View className='conversation-footer'>
                  <Text className='last-message' numberOfLines={1}>
                    {conversation.lastMessage}
                  </Text>
                </View>
                {conversation.childName && <Text className='conversation-meta'>{conversation.childName}</Text>}
              </View>
            </View>
          ))}
        </ScrollView>
      )}
    </View>
  )
}
