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

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

  useEffect(() => {
    loadConversations()
  }, [])

  const loadConversations = async () => {
    const data = await getConversations()
    setConversations(data)
  }

  const handleConversationClick = (conversation: ChatConversation) => {
    Taro.navigateTo({
      url: `/pages/chat/detail/index?id=${conversation.id}&name=${encodeURIComponent(conversation.name)}`
    })
  }

  return (
    <View className='chat-page'>
      <View className='page-header'>
        <Text className='page-title'>AI 玩伴</Text>
        <Text className='page-subtitle'>选择玩伴开始对话</Text>
      </View>

      <ScrollView className='conversation-list' scrollY>
        {conversations.map((conversation) => (
          <View
            key={conversation.id}
            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'>
                <Text className='conversation-name'>{conversation.name}</Text>
                <Text className='conversation-time'>{conversation.time}</Text>
              </View>
              <View className='conversation-footer'>
                <Text className='last-message' numberOfLines={1}>
                  {conversation.lastMessage}
                </Text>
                {conversation.unreadCount && conversation.unreadCount > 0 && (
                  <View className='unread-badge'>
                    <Text className='unread-count'>{conversation.unreadCount}</Text>
                  </View>
                )}
              </View>
            </View>
          </View>
        ))}
      </ScrollView>
    </View>
  )
}
