import React, { useState, useEffect } from 'react'
import { View, Text, Image, Input } from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import { useUser } from '@/hooks/useUser'
import { useScrollHeight } from '@/hooks/useScrollHeight'
import { getRegisterPayInfo, getMyRegisterStatus, RegisterPayInfo } from '@/api/shop/shopMemberRegister'
import { getUserInfo } from '@/api/passport/login'
import PayModal from '@/components/business/PayModal'

definePageConfig({
  navigationBarTitleText: '支付注册费',
})

const RegisterPayPage: React.FC = () => {
  const router = useRouter()
  const { user, isLoggedIn, refreshUser } = useUser()
  const scrollHeight = useScrollHeight()
  const [loading, setLoading] = useState(true)
  const [payInfo, setPayInfo] = useState<RegisterPayInfo | null>(null)
  const [showPayModal, setShowPayModal] = useState(false)
  const [userStatus, setUserStatus] = useState<any>(null)

  // 获取URL参数
  const phone = router.params.phone || ''
  const registerId = router.params.registerId ? Number(router.params.registerId) : 0

  useEffect(() => {
    if (!isLoggedIn) {
      Taro.navigateTo({ url: '/passport/login' })
      return
    }
    checkAndFetchData()
  }, [isLoggedIn])

  // 检查用户状态并获取支付信息
  const checkAndFetchData = async () => {
    try {
      setLoading(true)

      // 检查当前用户状态
      const status = await getMyRegisterStatus()
      setUserStatus(status)

      // 如果已经是会员，跳转到会员中心
      if (status?.isDealer) {
        Taro.showModal({
          title: '提示',
          content: '您已经是会员，无需再次支付注册费',
          showCancel: false,
          success: () => {
            Taro.navigateBack()
          },
        })
        return
      }

      // 获取支付信息
      if (phone) {
        const info = await getRegisterPayInfo(phone)
        if (info) {
          setPayInfo(info)
        } else {
          Taro.showToast({ title: '未找到支付信息，请联系上级会员', icon: 'none' })
        }
      } else {
        // 如果没有传入手机号，尝试获取当前用户的注册记录
        if (status?.register) {
          setPayInfo({
            id: status.register.id,
            phone: status.register.phone,
            realName: status.register.realName,
            registerFee: status.register.registerFee,
            dealerName: status.register.dealerName,
            dealerPhone: status.register.dealerPhone,
          })
        }
      }
    } catch (e: any) {
      console.error('获取数据失败:', e)
      Taro.showToast({ title: e.message || '获取数据失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  // 发起支付
  const handlePay = () => {
    if (!payInfo) {
      Taro.showToast({ title: '支付信息加载中，请稍候', icon: 'none' })
      return
    }
    setShowPayModal(true)
  }

  // 支付成功回调
  const handlePaySuccess = async () => {
    setShowPayModal(false)
    Taro.showModal({
      title: '支付成功',
      content: '恭喜！您已成为平台会员，请使用手机号登录查看。',
      showCancel: false,
      success: () => {
        // 刷新用户信息
        refreshUser?.()
        Taro.redirectTo({ url: '/pages/user/index' })
      },
    })
  }

  // 支付失败回调
  const handlePayFail = (err: string) => {
    setShowPayModal(false)
    Taro.showToast({ title: err || '支付失败', icon: 'none' })
  }

  if (!isLoggedIn) return null

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

  return (
    <View className='min-h-screen bg-gray-50'>
      <View className='p-4' style={{ height: scrollHeight }}>
        {/* 支付卡片 */}
        <View className='bg-white rounded-2xl overflow-hidden shadow-sm'>
          {/* 顶部背景 */}
          <View
            className='p-6 text-center'
            style={{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }}
          >
            <Text className='text-white text-sm'>注册费</Text>
            <View className='flex items-center justify-center mt-2'>
              <Text className='text-white text-3xl font-bold'>¥</Text>
              <Text className='text-white text-5xl font-bold ml-1'>198</Text>
              <Text className='text-white text-xl font-medium ml-1'>.00</Text>
            </View>
          </View>

          {/* 支付信息 */}
          <View className='p-4'>
            <View className='flex items-start gap-3 mb-4'>
              <View className='w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0'>
                <Text className='text-base'>💡</Text>
              </View>
              <View>
                <Text className='text-gray-800 text-sm font-medium block'>成为平台会员</Text>
                <Text className='text-gray-500 text-xs mt-1 block leading-relaxed'>
                  支付注册费后，您将成为平台正式会员，享受会员专属权益和分佣待遇。
                </Text>
              </View>
            </View>

            {/* 费用明细 */}
            <View className='bg-gray-50 rounded-xl p-4 mb-4'>
              <Text className='text-gray-600 text-sm font-medium mb-3 block'>费用明细</Text>
              <View className='space-y-2'>
                <View className='flex justify-between'>
                  <Text className='text-gray-500 text-sm'>会员费(上级代收)</Text>
                  <Text className='text-gray-600 text-sm'>¥298.00</Text>
                </View>
                <View className='flex justify-between'>
                  <Text className='text-gray-500 text-sm'>注册费(平台收取)</Text>
                  <Text className='text-gray-600 text-sm'>¥198.00</Text>
                </View>
                <View className='border-t border-gray-200 pt-2 flex justify-between'>
                  <Text className='text-gray-700 text-sm font-medium'>合计</Text>
                  <Text className='text-orange-500 text-base font-bold'>¥496.00</Text>
                </View>
              </View>
            </View>

            {/* 提示 */}
            <View className='bg-orange-50 rounded-xl p-3 mb-4'>
              <Text className='text-xs text-orange-600 leading-relaxed block'>
                ⚠️ 会员费(¥298)由上级会员线下收取，请联系您的上级确认。注册费(¥198)通过平台支付。
              </Text>
            </View>

            {/* 会员权益 */}
            <View className='mb-4'>
              <Text className='text-gray-600 text-sm font-medium mb-3 block'>会员权益</Text>
              <View className='grid grid-cols-2 gap-2'>
                {[
                  { icon: '💰', text: '下级消费获得佣金' },
                  { icon: '🎁', text: '兑换权益包' },
                  { icon: '📈', text: '团队业绩统计' },
                  { icon: '💳', text: '佣金提现到微信' },
                ].map((item, idx) => (
                  <View key={idx} className='flex items-center gap-2 bg-gray-50 rounded-lg p-2'>
                    <Text className='text-base'>{item.icon}</Text>
                    <Text className='text-gray-600 text-xs'>{item.text}</Text>
                  </View>
                ))}
              </View>
            </View>
          </View>
        </View>

        {/* 下一步按钮 */}
        <View className='mt-6'>
          <View
            className='rounded-full py-4 text-center'
            style={{ backgroundColor: '#667eea' }}
            onClick={handlePay}
          >
            <Text className='text-white text-lg font-medium'>立即支付 ¥198.00</Text>
          </View>
        </View>

        {/* 联系客服 */}
        <View className='mt-4 text-center'>
          <Text
            className='text-gray-400 text-sm'
            onClick={() => Taro.navigateTo({ url: '/pages/user/customer-service/index' })}
          >
            遇到问题？联系客服
          </Text>
        </View>
      </View>

      {/* 支付弹窗 */}
      {showPayModal && payInfo && (
        <PayModal
          amount={payInfo.registerFee || 198}
          subject='注册费'
          onSuccess={handlePaySuccess}
          onFail={handlePayFail}
          onClose={() => setShowPayModal(false)}
        />
      )}
    </View>
  )
}

export default RegisterPayPage
