import React, { useState } from 'react'
import { View, Text, Input, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { bindGiftCard } from '@/api/shop/shopGiftCard'
import request from '@/utils/request'
import { useScrollHeight } from '@/hooks/useScrollHeight'

definePageConfig({
  navigationBarTitleText: '兑换礼品卡',
})

const GiftCardExchangePage: React.FC = () => {
  const scrollHeight = useScrollHeight(44)
  const [code, setCode] = useState('')
  const [step, setStep] = useState(1) // 1:输入兑换码, 2:确认兑换
  const [cardInfo, setCardInfo] = useState({
    code: '',
    amount: 200,
    fromUser: '张三',
    expireDate: '2029-05-12',
  })

  // 查询礼品卡
  const handleQuery = async () => {
    if (!code.trim()) {
      Taro.showToast({ title: '请输入兑换码', icon: 'none' })
      return
    }

    if (code.length < 8) {
      Taro.showToast({ title: '兑换码格式错误', icon: 'none' })
      return
    }

    Taro.showLoading({ title: '查询中...' })
    try {
      // 调用 API 查询礼品卡信息
      const res = await request.get<{ code: number; data: any }>(`/shop/shop-gift/by-code/${code}`)
      Taro.hideLoading()
      
      if (res.code === 0 && res.data) {
        setCardInfo({
          code: res.data.code || code,
          amount: res.data.faceValue || 0,
          fromUser: res.data.nickName || '未知用户',
          expireDate: res.data.takeTime || '无限制',
        })
        setStep(2)
        Taro.showToast({ title: '查询成功', icon: 'success' })
      } else {
        Taro.showToast({ title: '礼品卡不存在', icon: 'none' })
      }
    } catch (err: any) {
      Taro.hideLoading()
      Taro.showToast({ title: err.message || '查询失败', icon: 'none' })
    }
  }

  // 确认兑换
  const handleExchange = async () => {
    Taro.showModal({
      title: '确认兑换',
      content: `确定兑换该礼品卡吗？\n面值：¥${cardInfo.amount}`,
      confirmText: '确认兑换',
      confirmColor: '#0e932e',
      success: async (res) => {
        if (res.confirm) {
          Taro.showLoading({ title: '兑换中...' })
          try {
            const result = await bindGiftCard(cardInfo.code)
            Taro.hideLoading()
            if (result.code === 0) {
              Taro.showToast({ title: '兑换成功', icon: 'success' })
              setTimeout(() => {
                Taro.navigateBack()
              }, 1500)
            } else {
              Taro.showToast({ title: result.message || '兑换失败', icon: 'none' })
            }
          } catch (err: any) {
            Taro.hideLoading()
            Taro.showToast({ title: err.message || '兑换失败', icon: 'none' })
          }
        }
      },
    })
  }

  // 重新输入
  const handleReset = () => {
    setCode('')
    setStep(1)
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      <ScrollView scrollY style={{ height: scrollHeight }}>
        {step === 1 ? (
          <>
            {/* 输入兑换码 */}
            <View className='mx-3 mt-3 bg-white rounded-xl p-4'>
              <Text className='text-base font-medium text-gray-800 mb-3 block'>
                输入兑换码
              </Text>
              
              <View className='bg-gray-50 rounded-lg p-4 mb-3'>
                <Input
                  type='text'
                  value={code}
                  onInput={(e) => setCode(e.detail.value.toUpperCase())}
                  placeholder='请输入礼品卡兑换码'
                  className='text-center text-lg font-bold tracking-widest'
                  maxlength={16}
                />
              </View>

              <View className='text-xs text-gray-400 mb-3'>
                <Text className='block'>• 兑换码通常为 12-16 位字符</Text>
                <Text className='block'>• 可在购买记录中查看兑换码</Text>
              </View>

              <View
                className={`text-center py-3 rounded-full ${
                  code.length >= 8 ? 'bg-purple-500' : 'bg-gray-300'
                }`}
                onClick={code.length >= 8 ? handleQuery : undefined}
              >
                <Text className='text-white font-bold'>查询礼品卡</Text>
              </View>
            </View>

            {/* 兑换说明 */}
            <View className='mx-3 mt-3 bg-white rounded-xl p-4'>
              <Text className='text-base font-medium text-gray-800 mb-3 block'>
                兑换说明
              </Text>
              <View className='text-xs text-gray-500 leading-6'>
                <Text className='block'>1. 兑换后金额将存入您的账户余额</Text>
                <Text className='block'>2. 礼品卡兑换后不可撤销</Text>
                <Text className='block'>3. 如有问题，请联系客服</Text>
              </View>
            </View>
          </>
        ) : (
          <>
            {/* 确认兑换 */}
            <View className='mx-3 mt-3 bg-white rounded-xl p-4'>
              <View className='text-center mb-4'>
                <Text className='text-4xl mb-2 block'>🎁</Text>
                <Text className='text-base font-bold text-gray-800 block'>
                  确认兑换
                </Text>
              </View>

              {/* 礼品卡信息 */}
              <View className='rounded-lg p-4 mb-3' style={{ background: 'linear-gradient(to right, #faf5ff, #fdf2f8)' }}>
                <View className='flex justify-between items-center mb-2'>
                  <Text className='text-sm text-gray-600'>礼品卡面值</Text>
                  <Text className='text-2xl font-bold text-purple-500'>
                    ¥{cardInfo.amount}
                  </Text>
                </View>
                <View className='flex justify-between items-center mb-2'>
                  <Text className='text-sm text-gray-600'>兑换码</Text>
                  <Text className='text-sm text-gray-800 font-mono'>{cardInfo.code}</Text>
                </View>
                <View className='flex justify-between items-center mb-2'>
                  <Text className='text-sm text-gray-600'>赠送人</Text>
                  <Text className='text-sm text-gray-800'>{cardInfo.fromUser}</Text>
                </View>
                <View className='flex justify-between items-center'>
                  <Text className='text-sm text-gray-600'>有效期至</Text>
                  <Text className='text-sm text-gray-800'>{cardInfo.expireDate}</Text>
                </View>
              </View>

              <View className='text-xs text-gray-400 mb-3 text-center'>
                兑换后金额将存入您的账户余额
              </View>

              <View className='flex gap-3'>
                <View
                  className='flex-1 text-center py-3 rounded-full bg-gray-200'
                  onClick={handleReset}
                >
                  <Text className='text-gray-700 font-bold'>重新输入</Text>
                </View>
                <View
                  className='flex-1 text-center py-3 rounded-full bg-purple-500'
                  onClick={handleExchange}
                >
                  <Text className='text-white font-bold'>确认兑换</Text>
                </View>
              </View>
            </View>
          </>
        )}
        
        <View className='h-6' />
      </ScrollView>
    </View>
  )
}

export default GiftCardExchangePage
