import { useState, useEffect } from 'react'
import { View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Avatar, Empty, Tabs, TabPane } from '@nutui/nutui-react-taro'
import './index.scss'

interface TeamMember {
  id: string
  nickname: string
  avatar: string
  joinTime: string
  level: number
  orderCount: number
  totalCommission: number
  status: 'active' | 'inactive'
}

interface TeamStats {
  totalMembers: number
  activeMembers: number
  level1Members: number
  level2Members: number
  totalCommission: number
  monthCommission: number
}

function MyTeam() {
  const [activeTab, setActiveTab] = useState('0')
  const [members, setMembers] = useState<TeamMember[]>([])
  const [stats, setStats] = useState<TeamStats>({
    totalMembers: 0,
    activeMembers: 0,
    level1Members: 0,
    level2Members: 0,
    totalCommission: 0,
    monthCommission: 0
  })
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: '我的团队'
    })
    loadTeamData()
  }, [])

  const loadTeamData = async () => {
    try {
      setLoading(true)
      // 模拟数据
      const mockMembers: TeamMember[] = [
        {
          id: '1',
          nickname: '张小明',
          avatar: 'https://img12.360buyimg.com/imagetools/jfs/t1/143702/31/16654/116794/5fc6f541Edebf8a57/4138097748889987.png',
          joinTime: '2024-01-15',
          level: 1,
          orderCount: 15,
          totalCommission: 150.50,
          status: 'active'
        },
        {
          id: '2',
          nickname: '李小红',
          avatar: 'https://img12.360buyimg.com/imagetools/jfs/t1/143702/31/16654/116794/5fc6f541Edebf8a57/4138097748889987.png',
          joinTime: '2024-01-10',
          level: 1,
          orderCount: 8,
          totalCommission: 89.20,
          status: 'active'
        },
        {
          id: '3',
          nickname: '王小华',
          avatar: 'https://img12.360buyimg.com/imagetools/jfs/t1/143702/31/16654/116794/5fc6f541Edebf8a57/4138097748889987.png',
          joinTime: '2024-01-08',
          level: 2,
          orderCount: 3,
          totalCommission: 25.80,
          status: 'inactive'
        },
        {
          id: '4',
          nickname: '赵小刚',
          avatar: 'https://img12.360buyimg.com/imagetools/jfs/t1/143702/31/16654/116794/5fc6f541Edebf8a57/4138097748889987.png',
          joinTime: '2024-01-05',
          level: 2,
          orderCount: 12,
          totalCommission: 98.60,
          status: 'active'
        }
      ]

      // 计算统计数据
      const totalMembers = mockMembers.length
      const activeMembers = mockMembers.filter(m => m.status === 'active').length
      const level1Members = mockMembers.filter(m => m.level === 1).length
      const level2Members = mockMembers.filter(m => m.level === 2).length
      const totalCommission = mockMembers.reduce((sum, m) => sum + m.totalCommission, 0)

      setTimeout(() => {
        setMembers(mockMembers)
        setStats({
          totalMembers,
          activeMembers,
          level1Members,
          level2Members,
          totalCommission,
          monthCommission: totalCommission * 0.3 // 模拟本月佣金
        })
        setLoading(false)
      }, 1000)
    } catch (error) {
      console.error('加载团队数据失败:', error)
      setLoading(false)
    }
  }

  const getFilteredMembers = () => {
    switch (activeTab) {
      case '1':
        return members.filter(member => member.level === 1)
      case '2':
        return members.filter(member => member.level === 2)
      case '3':
        return members.filter(member => member.status === 'active')
      default:
        return members
    }
  }

  const handleMemberClick = (member: TeamMember) => {
    Taro.showModal({
      title: '成员详情',
      content: `
昵称：${member.nickname}
加入时间：${member.joinTime}
等级：${member.level}级下线
订单数量：${member.orderCount}
累计佣金：¥${member.totalCommission.toFixed(2)}
状态：${member.status === 'active' ? '活跃' : '不活跃'}
      `.trim(),
      showCancel: false
    })
  }

  if (loading) {
    return (
      <View className="my-team-page">
        <View className="loading-container">
          <View className="text-center text-gray-500">加载中...</View>
        </View>
      </View>
    )
  }

  return (
    <View className="my-team-page">
      {/* 团队统计 */}
      <View className="team-stats">
        <View className="stats-grid">
          <View className="stat-item">
            <View className="stat-value">{stats.totalMembers}</View>
            <View className="stat-label">团队总人数</View>
          </View>
          <View className="stat-item">
            <View className="stat-value">{stats.activeMembers}</View>
            <View className="stat-label">活跃成员</View>
          </View>
          <View className="stat-item">
            <View className="stat-value">¥{stats.totalCommission.toFixed(2)}</View>
            <View className="stat-label">累计佣金</View>
          </View>
          <View className="stat-item">
            <View className="stat-value">¥{stats.monthCommission.toFixed(2)}</View>
            <View className="stat-label">本月佣金</View>
          </View>
        </View>
      </View>

      {/* 等级统计 */}
      <View className="level-stats">
        <View className="level-item">
          <View className="level-info">
            <View className="level-title">一级下线</View>
            <View className="level-count">{stats.level1Members}人</View>
          </View>
        </View>
        <View className="level-item">
          <View className="level-info">
            <View className="level-title">二级下线</View>
            <View className="level-count">{stats.level2Members}人</View>
          </View>
        </View>
      </View>

      {/* 成员列表 */}
      <View className="members-container">
        <Tabs value={activeTab} onChange={(value) => setActiveTab(value)}>
          <TabPane title="全部" />
          <TabPane title="一级" />
          <TabPane title="二级" />
          <TabPane title="活跃" />
        </Tabs>

        <View className="members-list">
          {getFilteredMembers().length === 0 ? (
            <View className="empty-container">
              <Empty description="暂无团队成员" />
            </View>
          ) : (
            getFilteredMembers().map((member) => (
              <View
                key={member.id}
                className="member-item"
                onClick={() => handleMemberClick(member)}
              >
                <Avatar size="50" src={member.avatar} shape="round" />
                <View className="member-info">
                  <View className="member-header">
                    <View className="member-name">{member.nickname}</View>
                    <View className={`member-level level-${member.level}`}>
                      {member.level}级
                    </View>
                  </View>
                  <View className="member-stats">
                    <View className="stat">订单：{member.orderCount}</View>
                    <View className="stat">佣金：¥{member.totalCommission.toFixed(2)}</View>
                  </View>
                  <View className="member-time">加入时间：{member.joinTime}</View>
                </View>
                <View className={`member-status ${member.status}`}>
                  {member.status === 'active' ? '活跃' : '不活跃'}
                </View>
              </View>
            ))
          )}
        </View>
      </View>
    </View>
  )
}

export default MyTeam
