import { View, Text, Image } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { distributorTeam } from '../../api'
import './team.scss'

export default function Team() {
  const [data, setData] = useState<any>(null)
  const [loading, setLoading] = useState(true)

  useLoad(() => {
    fetchData()
  })

  const fetchData = async () => {
    try {
      const res = await distributorTeam()
      setData(res)
    } catch (err) {
      console.error(err)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  if (loading) return <View className='page-container'>Loading...</View>
  if (!data) return <View className='page-container'>Error</View>

  return (
    <View className='page-container'>
      <View className='header'>
        <View className='stat'>
           <Text className='val'>{data.children_count}</Text>
           <Text className='lbl'>直推人数</Text>
        </View>
        <View className='stat'>
           <Text className='val'>¥{data.second_level_earnings}</Text>
           <Text className='lbl'>团队贡献收益</Text>
        </View>
      </View>

      <View className='list'>
        <View className='list-header'>我的团队成员</View>
        {data.children?.length > 0 ? (
            data.children.map((item: any) => (
                <View className='item' key={item.id}>
                    <Image className='avatar' src={item.user_info?.avatar_url || ''} />
                    <View className='info'>
                        <Text className='name'>{item.user_info?.nickname || '用户'}</Text>
                        <Text className='time'>加入时间: {item.created_at?.split('T')[0]}</Text>
                    </View>
                    <Text className='level'>Lv.{item.level}</Text>
                </View>
            ))
        ) : (
            <View className='empty'>暂无成员</View>
        )}
      </View>
    </View>
  )
}
