import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useUser } from '@/hooks/useUser'
import { useScrollHeight } from '@/hooks/useScrollHeight'
import { listShopUserReferee } from '@/api/shop/shopUserReferee'
import type { ShopUserReferee } from '@/api/shop/shopUserReferee/model'
import EmptyState from '@/components/common/EmptyState'

definePageConfig({
  navigationBarTitleText: '我的团队',
})

const TeamPage: React.FC = () => {
  const { isLoggedIn } = useUser()
  const [teamMembers, setTeamMembers] = useState<ShopUserReferee[]>([])
  const [loading, setLoading] = useState(true)
  const scrollHeight = useScrollHeight(44)


  useEffect(() => {
    if (!isLoggedIn) {
      Taro.navigateTo({ url: '/passport/login' })
      return
    }
    fetchTeamMembers()
  }, [isLoggedIn])

  const fetchTeamMembers = async () => {
    try {
      const data = await listShopUserReferee({})
      setTeamMembers(data || [])
    } catch (e) {
      console.error('获取团队信息失败:', e)
    } finally {
      setLoading(false)
    }
  }

  if (!isLoggedIn) {
    return null
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      <ScrollView scrollY style={{ height: scrollHeight }}>
        {/* 团队统计 */}
        <View className='mx-3 mt-3 p-4 bg-white rounded-lg'>
          <View className='flex justify-around'>
            <View className='text-center'>
              <Text className='text-2xl font-bold text-green-600 block'>
                {teamMembers.length}
              </Text>
              <Text className='text-xs text-gray-500'>团队人数</Text>
            </View>
            <View className='text-center'>
              <Text className='text-2xl font-bold text-blue-500 block'>
                {teamMembers.filter(m => m.isActive).length}
              </Text>
              <Text className='text-xs text-gray-500'>活跃成员</Text>
            </View>
            <View className='text-center'>
              <Text className='text-2xl font-bold text-orange-500 block'>
                {teamMembers.filter(m => m.isMember).length}
              </Text>
              <Text className='text-xs text-gray-500'>会员人数</Text>
            </View>
          </View>
        </View>

        {/* 团队成员列表 */}
        <View className='mx-3 mt-3'>
          <Text className='text-base font-medium text-gray-800 mb-2 block'>团队成员</Text>
          {loading ? (
            <View className='flex items-center justify-center py-10'>
              <Text className='text-gray-400'>加载中...</Text>
            </View>
          ) : teamMembers.length === 0 ? (
            <EmptyState text='暂无团队成员' />
          ) : (
            <View className='bg-white rounded-lg overflow-hidden'>
              {teamMembers.map((member, idx) => (
                <View
                  key={member.id}
                  className={`flex items-center px-4 py-3 ${
                    idx < teamMembers.length - 1 ? 'border-b border-gray-50' : ''
                  }`}
                >
                  <Image
                    className='w-10 h-10 rounded-full bg-gray-100'
                    src={member.avatar}
                    mode='aspectFill'
                  />
                  <View className='flex-1 ml-3'>
                    <View className='flex items-center gap-2'>
                      <Text className='text-sm font-medium text-gray-800'>
                        {member.nickname || '用户'}
                      </Text>
                      {member.isMember && (
                        <View className='px-1 py-0 bg-orange-500 rounded'>
                          <Text className='text-xs text-white'>会员</Text>
                        </View>
                      )}
                    </View>
                    <Text className='text-xs text-gray-400'>
                      加入时间：{member.createTime}
                    </Text>
                  </View>
                  <View className='text-right'>
                    <Text className='text-sm font-medium text-green-500'>
                      ¥{member.totalCommission || 0}
                    </Text>
                    <Text className='text-xs text-gray-400 block'>累计佣金</Text>
                  </View>
                </View>
              ))}
            </View>
          )}
        </View>

        <View className='h-6' />
      </ScrollView>
    </View>
  )
}

export default TeamPage
