import React, { useState, useEffect } from 'react'
import { View, Text, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useUser } from '@/hooks/useUser'
import { useRequest } from '@/hooks/useRequest'
import { getMemberCenterData, type MemberCenterData } from '@/api/shop/shopMemberCenter'
import { listShopUserReferee } from '@/api/shop/shopUserReferee'
import MemberBadge from '@/components/business/MemberBadge'

definePageConfig({
  navigationBarTitleText: '会员中心',
})

const MemberPage: React.FC = () => {
  const { user, isLoggedIn } = useUser()

  // 获取会员中心数据
  const { data: memberData, run: runMemberData, loading: memberLoading } = useRequest(getMemberCenterData, {
    manual: true,
  })

  // 获取团队成员数据
  const { data: teamData, run: runTeamData } = useRequest(listShopUserReferee, {
    manual: true,
  })

  // 登录后加载数据
  useEffect(() => {
    if (!isLoggedIn) {
      Taro.navigateTo({ url: '/passport/login' })
      return
    }
    runMemberData()
    runTeamData({})
  }, [isLoggedIn])

  // 处理升级会员
  const handleUpgrade = () => {
    Taro.navigateTo({ url: '/pages/user/member-upgrade/index' })
  }

  // 处理功能项点击
  const handleFeatureClick = (url: string) => {
    if (url) {
      Taro.navigateTo({ url })
    }
  }

  // 会员功能菜单
  const memberFeatures = [
    {
      icon: '💰',
      label: '我的佣金',
      value: memberData?.commission !== undefined ? `¥${memberData.commission}` : '--',
      url: '/pages/user/commission/index',
    },
    {
      icon: '📊',
      label: '佣金明细',
      value: '',
      url: '/pages/user/commission/index',
    },
    {
      icon: '👥',
      label: '我的团队',
      value: memberData?.teamCount !== undefined ? `${memberData.teamCount}人` : '--',
      url: '/pages/user/team/index',
    },
    {
      icon: '📋',
      label: '邀请记录',
      value: '',
      url: '/pages/user/invite-record/index',
    },
  ]

  // 会员权益
  const memberBenefits = [
    { icon: '🎁', text: '享受会员专属折扣' },
    { icon: '💵', text: '获得分销佣金权益' },
    { icon: '🎯', text: '优先客服支持' },
    { icon: '🎉', text: '专属活动邀请' },
  ]

  if (!isLoggedIn) {
    return null
  }

  return (
    <View className='flex flex-col bg-gray-50 min-h-screen'>
        {/* 会员卡片 - 渐变背景 */}
        <View className='mx-3 mt-3 p-5 rounded-2xl relative overflow-hidden'
          style={{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }}>
          {/* 装饰圆形 */}
          <View className='absolute -right-6 -top-6 w-32 h-32 rounded-full opacity-10 bg-white' />
          <View className='absolute -left-4 -bottom-4 w-24 h-24 rounded-full opacity-10 bg-white' />

          <View className='relative z-10'>
            {/* 用户信息行 */}
            <View className='flex items-center justify-between mb-4'>
              <View className='flex items-center gap-3'>
                {user?.avatar ? (
                  <Image className='w-12 h-12 rounded-full border-2 border-white' src={user.avatar} mode='aspectFill' />
                ) : (
                  <View className='w-12 h-12 rounded-full bg-white bg-opacity-30 flex items-center justify-center'>
                    <Text className='text-xl text-white'>👤</Text>
                  </View>
                )}
                <View>
                  <Text className='text-white text-lg font-bold'>{user?.nickname || user?.phone || '用户'}</Text>
                  <View className='flex items-center gap-2 mt-1'>
                    <MemberBadge levelName={memberData?.memberLevel || user?.memberLevelName || '普通会员'} />
                  </View>
                </View>
              </View>
              {/* 升级按钮 */}
              <View
                className='px-3 py-1.5 rounded-full flex items-center gap-1'
                style={{ backgroundColor: 'rgba(255,255,255,0.25)' }}
                onClick={handleUpgrade}
              >
                <Text className='text-white text-xs'>{memberData?.isDealer ? '已开通' : '升级会员'}</Text>
                <Text className='text-white text-xs'>→</Text>
              </View>
            </View>

            {/* 佣金数据 */}
            <View className='flex justify-around pt-4 border-t border-white border-opacity-20'>
              <View className='text-center'>
                <Text className='text-white text-2xl font-bold block'>
                  {memberLoading ? '...' : (memberData?.totalCommission || 0).toFixed(2)}
                </Text>
                <Text className='text-white text-xs opacity-80 mt-1'>累计佣金(元)</Text>
              </View>
              <View className='w-px bg-white opacity-20' />
              <View className='text-center'>
                <Text className='text-white text-2xl font-bold block'>
                  {memberLoading ? '...' : (memberData?.commission || 0).toFixed(2)}
                </Text>
                <Text className='text-white text-xs opacity-80 mt-1'>可提现(元)</Text>
              </View>
              <View className='w-px bg-white opacity-20' />
              <View className='text-center'>
                <Text className='text-white text-2xl font-bold block'>
                  {memberLoading ? '...' : (memberData?.teamCount || 0)}
                </Text>
                <Text className='text-white text-xs opacity-80 mt-1'>团队人数</Text>
              </View>
            </View>
          </View>
        </View>

        {/* 功能入口卡片 */}
        <View className='bg-white mx-3 mt-3 rounded-xl overflow-hidden'>
          <View className='px-4 py-3 border-b border-gray-100'>
            <Text className='text-base font-medium text-gray-800'>分销管理</Text>
          </View>
          {memberFeatures.map((item, idx) => (
            <View
              key={item.label}
              className={`flex items-center justify-between px-4 py-3 ${
                idx < memberFeatures.length - 1 ? 'border-b border-gray-50' : ''
              }`}
              onClick={() => handleFeatureClick(item.url)}
            >
              <View className='flex items-center gap-3'>
                <Text className='text-xl'>{item.icon}</Text>
                <Text className='text-sm text-gray-700'>{item.label}</Text>
              </View>
              <View className='flex items-center gap-2'>
                {item.value && (
                  <Text className='text-sm font-medium text-orange-500'>{item.value}</Text>
                )}
                <Text className='text-gray-300 text-sm'>›</Text>
              </View>
            </View>
          ))}
        </View>

        {/* 会员权益 */}
        <View className='bg-white mx-3 mt-3 p-4 rounded-xl'>
          <View className='flex items-center justify-between mb-3'>
            <Text className='text-base font-medium text-gray-800'>会员权益</Text>
            <Text
              className='text-xs text-blue-500'
              onClick={() => Taro.navigateTo({ url: '/pages/user/member-upgrade/index' })}
            >
              了解更多 ›
            </Text>
          </View>
          <View className='grid grid-cols-2 gap-3'>
            {memberBenefits.map((benefit, idx) => (
              <View key={idx} className='flex items-center gap-2 bg-gray-50 rounded-lg px-3 py-2'>
                <Text className='text-lg'>{benefit.icon}</Text>
                <Text className='text-xs text-gray-600 flex-1'>{benefit.text}</Text>
              </View>
            ))}
          </View>
        </View>

        {/* 推广赚钱 */}
        <View className='bg-white mx-3 mt-3 p-4 rounded-xl'>
          <Text className='text-base font-medium text-gray-800 mb-3 block'>推广赚钱</Text>
          <View className='bg-gradient-to-r from-orange-50 to-red-50 rounded-xl p-4'>
            <View className='flex items-start gap-3'>
              <View className='w-12 h-12 rounded-full bg-orange-100 flex items-center justify-center'>
                <Text className='text-2xl'>🎁</Text>
              </View>
              <View className='flex-1'>
                <Text className='text-orange-600 font-medium block'>邀请好友赚佣金</Text>
                <Text className='text-gray-500 text-xs mt-1 block'>
                  每邀请1位好友注册并消费，可获得佣金分成
                </Text>
                <View className='flex gap-2 mt-2'>
                  <View
                    className='px-3 py-1.5 bg-orange-500 rounded-full'
                    onClick={() => Taro.navigateTo({ url: '/pages/user/promotion/index' })}
                  >
                    <Text className='text-white text-xs'>立即推广</Text>
                  </View>
                  <View
                    className='px-3 py-1.5 border border-orange-500 rounded-full'
                    onClick={() => Taro.navigateTo({ url: '/pages/user/invite-record/index' })}
                  >
                    <Text className='text-orange-500 text-xs'>邀请记录</Text>
                  </View>
                </View>
              </View>
            </View>
          </View>
        </View>

        {/* 团队概况 */}
        {teamData && teamData.length > 0 && (
          <View className='bg-white mx-3 mt-3 p-4 rounded-xl'>
            <View className='flex items-center justify-between mb-3'>
              <Text className='text-base font-medium text-gray-800'>团队概况</Text>
              <Text
                className='text-xs text-blue-500'
                onClick={() => Taro.navigateTo({ url: '/pages/user/team/index' })}
              >
                查看全部 ›
              </Text>
            </View>
            <View className='grid grid-cols-3 gap-2'>
              <View className='bg-blue-50 rounded-lg p-3 text-center'>
                <Text className='text-blue-600 text-xl font-bold block'>{teamData.length}</Text>
                <Text className='text-gray-500 text-xs mt-1'>团队人数</Text>
              </View>
              <View className='bg-green-50 rounded-lg p-3 text-center'>
                <Text className='text-green-600 text-xl font-bold block'>
                  {teamData.filter(m => (m as any)?.isActive).length}
                </Text>
                <Text className='text-gray-500 text-xs mt-1'>活跃成员</Text>
              </View>
              <View className='bg-purple-50 rounded-lg p-3 text-center'>
                <Text className='text-purple-600 text-xl font-bold block'>
                  {teamData.filter(m => (m as any)?.isMember).length}
                </Text>
                <Text className='text-gray-500 text-xs mt-1'>会员人数</Text>
              </View>
            </View>
          </View>
        )}

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

export default MemberPage
