import React, { useState, useEffect, useCallback } from 'react'
import { View, Text, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useUser } from '@/hooks/useUser'
import { pageAllApps, pagePublishReviews } from '@/api/app/appProduct'
import { getAllTickets } from '@/api/app/ticket'
import { pageUsers } from '@/api/system/user'
import { getPageTotal, getPageList } from '@/utils/devcenter'
import Badge from '@/components/common/Badge'

definePageConfig({
  navigationBarTitleText: '平台管理',
})

// 功能卡片定义（与门店中心同款结构：图标 + 标题 + 描述 + 角标 + 跳转）
const FEATURE_CARDS = [
  {
    key: 'app-review',
    icon: '📝',
    title: '应用审核',
    desc: '审核开发者提交的应用上架',
    url: '/pages/admin/app-review/index',
    color: '#3b82f6',
    bgColor: '#dbeafe',
    showBadge: true,
  },
  {
    key: 'git-review',
    icon: '🐙',
    title: 'Git 审核',
    desc: '审核 Git 仓库接入申请',
    url: '/pages/admin/git-review/index',
    color: '#8b5cf6',
    bgColor: '#ede9fe',
    showBadge: false,
  },
  {
    key: 'domain-review',
    icon: '🌐',
    title: '域名审核',
    desc: '审核自定义域名绑定',
    url: '/pages/admin/domain-review/index',
    color: '#0891b2',
    bgColor: '#cffafe',
    showBadge: false,
  },
  {
    key: 'tickets',
    icon: '🎫',
    title: '工单处理',
    desc: '处理用户提交的工单',
    url: '/pages/admin/tickets/index',
    color: '#f59e0b',
    bgColor: '#fef3c7',
    showBadge: true,
  },
]

export default function AdminCenterPage() {
  const { user, isLoggedIn, loading: userLoading } = useUser()
  const isSuperAdmin = (user as any)?.isSuperAdmin === true

  const [dataLoading, setDataLoading] = useState(true)
  const [pendingApps, setPendingApps] = useState(0)
  const [pendingTickets, setPendingTickets] = useState(0)
  const [overview, setOverview] = useState({ apps: 0, users: 0, tickets: 0 })

  useEffect(() => {
    if (isLoggedIn && isSuperAdmin) {
      load()
    } else {
      setDataLoading(false)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isLoggedIn, isSuperAdmin])

  /** 加载角标数量与平台概况 */
  const load = useCallback(async () => {
    setDataLoading(true)
    try {
      const [appsR, pendR, allR, usersR] = await Promise.allSettled([
        pageAllApps({ page: 1, limit: 1 }),
        pagePublishReviews({ page: 1, limit: 1 }),
        getAllTickets({ page: 1, limit: 100 }),
        pageUsers({ page: 1, limit: 1 } as any),
      ])

      // 待审核应用（pagePublishReviews 已按 pending_review 过滤）
      const pendingAppsCount = pendR.status === 'fulfilled' ? getPageTotal(pendR.value) : 0
      setPendingApps(pendingAppsCount)

      // 工单：总数 + 待处理（未解决/未关闭）
      const ticketData = allR.status === 'fulfilled' ? allR.value : null
      const ticketList = ticketData ? getPageList(ticketData) : []
      const pendingTicketsCount = ticketList.filter(
        (t: any) => t.status !== 'resolved' && t.status !== 'closed'
      ).length
      setPendingTickets(pendingTicketsCount)

      const appsTotal = appsR.status === 'fulfilled' ? getPageTotal(appsR.value) : 0
      const ticketsTotal = ticketData ? getPageTotal(ticketData) : 0
      const usersTotal = usersR.status === 'fulfilled' ? getPageTotal(usersR.value) : 0
      setOverview({ apps: appsTotal, users: usersTotal, tickets: ticketsTotal })
    } catch {
      // ignore
    } finally {
      setDataLoading(false)
    }
  }, [])

  /** 获取卡片角标数字 */
  const getBadgeCount = (key: string) => {
    if (key === 'app-review') return pendingApps
    if (key === 'tickets') return pendingTickets
    return 0
  }

  if (userLoading || dataLoading) {
    return (
      <View className='min-h-full bg-gray-50 flex items-center justify-center'>
        <Text className='text-gray-400'>加载中...</Text>
      </View>
    )
  }

  if (!isLoggedIn) {
    return (
      <View className='min-h-full bg-gray-50 flex flex-col items-center justify-center py-24'>
        <Text className='text-5xl mb-3'>🔐</Text>
        <Text className='text-base text-gray-700 mb-2'>请先登录</Text>
        <Text className='text-xs text-gray-400 text-center'>登录后即可进入平台管理</Text>
      </View>
    )
  }

  if (!isSuperAdmin) {
    return (
      <View className='min-h-full bg-gray-50 flex flex-col items-center justify-center py-20 px-10'>
        <Text className='text-5xl mb-3'>🛡️</Text>
        <Text className='text-base text-gray-700 mb-2'>无访问权限</Text>
        <Text className='text-xs text-gray-400 text-center'>平台管理仅对超级管理员开放</Text>
      </View>
    )
  }

  const adminName = (user as any)?.nickname || (user as any)?.username || '平台管理员'
  const adminPhone = (user as any)?.phone

  return (
    <View className='min-h-full bg-gray-50'>

      {/* 顶部信息区：管理员头像 + 平台名称（与门店中心同款渐变头部） */}
      <View
        className='pt-8 pb-12 px-5 rounded-b-3xl relative overflow-hidden'
        style={{ background: 'linear-gradient(135deg, #15803d 0%, #22c55e 60%, #4ade80 100%)' }}
      >
        <View className='absolute -top-10 -right-10 w-40 h-40 rounded-full opacity-10'
          style={{ background: 'radial-gradient(circle, #ffffff, transparent)' }} />
        <View className='absolute -bottom-6 -left-6 w-24 h-24 rounded-full opacity-15'
          style={{ background: 'radial-gradient(circle, #ffffff, transparent)' }} />
        <View className='relative z-10 flex items-center gap-4'>
          {/* 管理员头像 */}
          <View className='w-16 h-16 rounded-full bg-white/20 border-2 border-white/40 overflow-hidden flex-shrink-0'>
            {((user as any)?.avatar) ? (
              <Image
                className='w-full h-full'
                src={(user as any).avatar}
                mode='aspectFill'
              />
            ) : (
              <View className='w-full h-full flex items-center justify-center'>
                <Text className='text-2xl'>👤</Text>
              </View>
            )}
          </View>

          {/* 平台信息 */}
          <View className='flex-1 min-w-0'>
            <Text className='text-white text-lg font-bold block truncate'>
              平台管理
            </Text>
            <Text className='text-white text-opacity-80 text-sm mt-1 block truncate'>
              {adminName}{adminPhone ? ` · ${adminPhone}` : ''}
            </Text>
          </View>
        </View>
      </View>

      {/* 功能卡片区（与门店中心同款） */}
      <View className='mx-3 -mt-6 relative z-20'>

        <View className='flex flex-col gap-3'>
          {FEATURE_CARDS.map(card => (
            <View
              key={card.key}
              className='bg-white rounded-xl p-4 flex items-center gap-4 active:opacity-80 relative'
              onClick={() => Taro.navigateTo({ url: card.url })}
            >
              {/* 图标 */}
              <View
                className='w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0'
                style={{ background: card.bgColor }}
              >
                <Text className='text-2xl'>{card.icon}</Text>
              </View>

              {/* 文字 */}
              <View className='flex-1 min-w-0'>
                <Text className='text-gray-800 text-base font-medium block'>{card.title}</Text>
                <Text className='text-gray-400 text-xs mt-0.5 block'>{card.desc}</Text>
              </View>

              {/* 待处理角标 */}
              {card.showBadge && (
                <Badge count={getBadgeCount(card.key)} className='absolute -top-1 -right-1' size={20} fontSize={11} fontWeight='bold' />
              )}

              {/* 箭头 */}
              <Text className='text-gray-300 text-lg flex-shrink-0'>›</Text>
            </View>
          ))}
        </View>
      </View>

      {/* 底部：平台概况（保留原页面统计信息，沿用同款卡片样式） */}
      <View className='mx-3 mt-6 mb-6'>
        <View className='bg-white rounded-xl p-4 flex items-center gap-3'>
          <View className='w-10 h-10 rounded-full bg-green-50 flex items-center justify-center flex-shrink-0'>
            <Text className='text-xl'>📊</Text>
          </View>
          <View className='flex-1 min-w-0'>
            <Text className='text-gray-800 text-sm font-medium block'>平台概况</Text>
            <Text className='text-gray-400 text-xs mt-0.5 block'>
              应用 {overview.apps} · 用户 {overview.users} · 工单 {overview.tickets}
            </Text>
          </View>
        </View>
      </View>
    </View>
  )
}
