import {useRef, useState} from 'react'
import Taro, {useDidShow} from '@tarojs/taro'
import {View, Text} from '@tarojs/components'
import {
  Avatar,
  Button,
  Empty,
  InfiniteLoading,
  Loading,
  PullToRefresh,
  SearchBar,
  Tag
} from '@nutui/nutui-react-taro'
import type {User} from '@/api/system/user/model'
import {pageUsers} from '@/api/system/user'
import {listUserRole, updateUserRole} from '@/api/system/userRole'
import {listRoles} from '@/api/system/role'

const PAGE_SIZE = 10

const AdminUsers = () => {
  const [searchValue, setSearchValue] = useState('')

  const [users, setUsers] = useState<User[]>([])
  const [loading, setLoading] = useState(false)
  const [hasMore, setHasMore] = useState(true)
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)

  const roleIdMapRef = useRef<Record<string, number>>({})
  const roleMapLoadedRef = useRef(false)

  const getRoleIdByCode = async (roleCode: string) => {
    if (!roleMapLoadedRef.current) {
      const roles = await listRoles()
      const nextMap: Record<string, number> = {}
      roles?.forEach(role => {
        if (role.roleCode && role.roleId) nextMap[role.roleCode] = role.roleId
      })
      roleIdMapRef.current = nextMap
      roleMapLoadedRef.current = true
    }
    return roleIdMapRef.current[roleCode]
  }

  const reload = async (isRefresh = false, overrideKeywords?: string) => {
    if (loading) return

    if (isRefresh) {
      setPage(1)
      setUsers([])
      setHasMore(true)
    }

    setLoading(true)
    try {
      const currentPage = isRefresh ? 1 : page
      const res = await pageUsers({
        page: currentPage,
        limit: PAGE_SIZE,
        keywords: overrideKeywords ?? searchValue
      })

      if (res?.list) {
        const nextUsers = isRefresh ? res.list : [...users, ...res.list]
        setUsers(nextUsers)
        setTotal(res.count || 0)
        setHasMore(res.list.length === PAGE_SIZE)
        setPage(isRefresh ? 2 : currentPage + 1)
      } else {
        setUsers([])
        setTotal(0)
        setHasMore(false)
      }
    } catch (error) {
      console.error('获取用户列表失败:', error)
      Taro.showToast({title: '获取用户列表失败', icon: 'error'})
    } finally {
      setLoading(false)
    }
  }

  const getUserRoleCodes = (target: User): string[] => {
    const fromRoles = target.roles?.map(r => r.roleCode).filter(Boolean) as string[] | undefined
    const fromSingle = target.roleCode ? [target.roleCode] : []
    const merged = [...(fromRoles || []), ...fromSingle].filter(Boolean)
    return Array.from(new Set(merged))
  }

  const getPrimaryRoleCode = (target: User): string | undefined => {
    const codes = getUserRoleCodes(target)
    if (codes.includes('superAdmin')) return 'superAdmin'
    if (codes.includes('admin')) return 'admin'
    if (codes.includes('dealer')) return 'dealer'
    if (codes.includes('user')) return 'user'
    return codes[0]
  }

  const renderRoleTag = (target: User) => {
    const code = getPrimaryRoleCode(target)
    if (code === 'superAdmin') return <Tag type="danger">超级管理员</Tag>
    if (code === 'admin') return <Tag type="danger">管理员</Tag>
    if (code === 'dealer') return <Tag type="primary">业务员</Tag>
    if (code === 'user') return <Tag type="success">注册会员</Tag>
    return <Tag>未知</Tag>
  }

  const toggleRole = async (target: User) => {
    const current = getPrimaryRoleCode(target)
    const nextRoleCode = current === 'dealer' ? 'user' : 'dealer'
    const nextRoleName = nextRoleCode === 'user' ? '注册会员' : '业务员'

    const confirmRes = await Taro.showModal({
      title: '确认切换角色',
      content: `确定将该用户切换为「${nextRoleName}」吗？`
    })
    if (!confirmRes.confirm) return

    try {
      const userId = target.userId
      if (!userId) return

      const nextRoleId = await getRoleIdByCode(nextRoleCode)
      if (!nextRoleId) {
        throw new Error(`未找到角色配置：${nextRoleCode}`)
      }

      const roles = await listUserRole({userId})
      const candidate = roles?.find(r => r.roleCode === 'dealer' || r.roleCode === 'user')

      if (candidate) {
        await updateUserRole({
          ...candidate,
          roleId: nextRoleId
        })
      } else {
        await updateUserRole({
          userId,
          roleId: nextRoleId
        })
      }

      Taro.showToast({title: '切换成功', icon: 'success'})
      await reload(true)
    } catch (error) {
      console.error('切换角色失败:', error)
      Taro.showToast({title: '切换失败', icon: 'error'})
    }
  }

  const handleSearch = (value: string) => {
    setSearchValue(value)
    reload(true, value).then()
  }

  const loadMore = async () => {
    if (!loading && hasMore) {
      await reload(false)
    }
  }

  useDidShow(() => {
    const init = async () => {
      try {
        await reload(true)
      } catch (error) {
        console.error('初始化失败:', error)
        Taro.showToast({title: '初始化失败', icon: 'error'})
      }
    }
    init().then()
  })

  return (
    <View className="bg-gray-50 min-h-screen">

      <View className="py-2 px-3">
        <SearchBar
          placeholder="搜索昵称/手机号/UID"
          value={searchValue}
          onChange={setSearchValue}
          onSearch={handleSearch}
        />
      </View>

      {total > 0 && (
        <View className="px-4 py-2 text-sm text-gray-500">
          共找到 {total} 个成员
        </View>
      )}

      <PullToRefresh onRefresh={() => reload(true)} headHeight={60}>
        <View className="px-4" style={{height: 'calc(100vh - 190px)', overflowY: 'auto'}} id="users-scroll">
          {users.length === 0 && !loading ? (
            <View className="flex flex-col justify-center items-center" style={{height: 'calc(100vh - 260px)'}}>
              <Empty description="暂无成员数据" style={{backgroundColor: 'transparent'}}/>
            </View>
          ) : (
            <InfiniteLoading
              target="users-scroll"
              hasMore={hasMore}
              onLoadMore={loadMore}
              loadingText={
                <View className="flex justify-center items-center py-4">
                  <Loading/>
                  <View className="ml-2">加载中...</View>
                </View>
              }
              loadMoreText={
                <View className="text-center py-4 text-gray-500">
                  {users.length === 0 ? '暂无数据' : '没有更多了'}
                </View>
              }
            >
              {users.map((item, index) => {
                const displayName = item.alias || item.nickname || item.realName || item.username || `用户${item.userId || ''}`
                const phone = item.phone || item.mobile || '-'
                const primaryRole = getPrimaryRoleCode(item)
                const toggleText = primaryRole === 'dealer' ? '设为注册会员' : '设为业务员'

                return (
                  <View key={item.userId || index} className="bg-white rounded-lg p-4 mb-3 shadow-sm">
                    <View className="flex items-center">
                      <Avatar size="40" src={item.avatar || item.avatarUrl} className="mr-3"/>
                      <View className="flex-1">
                        <View className="flex items-center justify-between">
                          <Text className="font-semibold text-gray-800">{displayName}</Text>
                          {renderRoleTag(item)}
                        </View>
                        <View className="text-xs text-gray-500 mt-1">
                          UID：{item.userId || '-'} · 手机：{phone}
                        </View>
                      </View>
                    </View>

                    <View className="flex justify-end gap-2 pt-3 mt-3 border-t border-gray-100">
                      <Button
                        size="small"
                        fill="outline"
                        onClick={() => toggleRole(item)}
                      >
                        {toggleText}
                      </Button>
                    </View>
                  </View>
                )
              })}
            </InfiniteLoading>
          )}
        </View>
      </PullToRefresh>
    </View>
  )
}

export default AdminUsers
