import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Button, Empty, Tabs, PullToRefresh, Avatar } from '@nutui/nutui-react-taro'
import { pageEnterpriseMember } from '@/api/developer/enterprise'
import type { EnterpriseMember } from '@/types/developer'
import './index.scss'

const EnterpriseMembers: React.FC = () => {
  const [activeTab, setActiveTab] = useState('all')
  const [members, setMembers] = useState<EnterpriseMember[]>([])
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)

  // 加载数据
  const loadData = async () => {
    try {
      setLoading(true)
      const result = await pageEnterpriseMember({ page: 1, limit: 20 })
      if (result) {
        setMembers(result.list || [])
      }
    } catch (error) {
      console.error('加载失败', error)
    } finally {
      setLoading(false)
    }
  }

  // 下拉刷新
  const onRefresh = async () => {
    setRefreshing(true)
    await loadData()
    setRefreshing(false)
  }

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

  // 筛选成员
  const filteredMembers = activeTab === 'all'
    ? members
    : members.filter((m) => {
        if (activeTab === 'owner') return m.role === 'owner'
        if (activeTab === 'admin') return m.role === 'admin'
        if (activeTab === 'member') return m.role === 'member'
        return true
      })

  // 获取角色标签
  const getRoleBadge = (role?: string) => {
    const badges: Record<string, { text: string; color: string; bg: string }> = {
      owner: { text: '所有者', color: '#d97706', bg: 'rgba(217, 119, 6, 0.1)' },
      admin: { text: '管理员', color: '#3b82f6', bg: 'rgba(59, 130, 246, 0.1)' },
      member: { text: '成员', color: '#6b7280', bg: 'rgba(107, 114, 128, 0.1)' },
    }
    return badges[role || 'member'] || badges.member
  }

  return (
    <View className="enterprise-members-page">
      <PullToRefresh refreshing={refreshing} onRefresh={onRefresh}>
        {/* 标签页 */}
        <View className="tabs-wrapper">
          <Tabs value={activeTab} onChange={(v) => setActiveTab(v as string)}>
            <Tabs.TabPane title="全部" value="all" />
            <Tabs.TabPane title="所有者" value="owner" />
            <Tabs.TabPane title="管理员" value="admin" />
            <Tabs.TabPane title="成员" value="member" />
          </Tabs>
        </View>

        <ScrollView scrollY className="enterprise-members-page__scroll">
          {/* 成员列表 */}
          <View className="member-list">
            {loading ? (
              <View className="member-list__loading">
                <Text>加载中...</Text>
              </View>
            ) : filteredMembers.length === 0 ? (
              <Empty description="暂无成员" />
            ) : (
              <View className="member-list__content">
                {filteredMembers.map((member) => {
                  const badge = getRoleBadge(member.role)
                  return (
                    <View key={member.id} className="member-card">
                      <Avatar size="80rpx" src={member.avatar} className="member-card__avatar">
                        {member.username?.charAt(0) || 'U'}
                      </Avatar>

                      <View className="member-card__info">
                        <View className="member-card__header">
                          <Text className="member-card__name">{member.username || '未知用户'}</Text>
                          <View className="member-card__badge" style={{ color: badge.color, backgroundColor: badge.bg }}>
                            <Text className="member-card__badgeText">{badge.text}</Text>
                          </View>
                        </View>

                        {member.department && (
                          <Text className="member-card__dept">{member.department}</Text>
                        )}

                        <Text className="member-card__time">
                          加入于 {member.inviteTime ? member.inviteTime.split(' ')[0] : '-'}
                        </Text>
                      </View>
                    </View>
                  )
                })}
              </View>
            )}
          </View>

          {/* 底部安全区域 */}
          <View className="safe-area-bottom" />
        </ScrollView>

        {/* 底部按钮 */}
        <View className="invite-btn-wrapper">
          <Button type="primary" block onClick={() => Taro.navigateTo({ url: '/enterprise/members/invite' })}>
            邀请成员
          </Button>
        </View>
      </PullToRefresh>
    </View>
  )
}

export default EnterpriseMembers
