import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { listMyGiftCards, getGiftCardBalance } from '@/api/shop/shopGiftCard'
import type { ShopGiftCard } from '@/api/shop/shopGiftCard/model'
import { useScrollHeight } from '@/hooks/useScrollHeight'

definePageConfig({
  navigationBarTitleText: '礼品卡余额',
})

const GiftCardBalancePage: React.FC = () => {
  const [balance, setBalance] = useState(0)
  const [cards, setCards] = useState<ShopGiftCard[]>([])
  const [loading, setLoading] = useState(true)
  const scrollHeight = useScrollHeight(44)


  // 加载礼品卡数据
  const loadGiftCards = async () => {
    try {
      // 并行请求余额和列表
      const [balanceRes, cardsRes] = await Promise.all([
        getGiftCardBalance(),
        listMyGiftCards()
      ])

      if (balanceRes.code === 0 && balanceRes.data) {
        setBalance(balanceRes.data.giftCards || 0)
      }

      if (cardsRes.code === 0 && cardsRes.data) {
        setCards(cardsRes.data)
      }
    } catch (e) {
      console.error('获取礼品卡失败:', e)
      Taro.showToast({ title: '获取数据失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadGiftCards()
  }, [])

  // 获取状态标签
  const getStatusLabel = (status?: number) => {
    const map: Record<number, { label: string; color: string }> = {
      1: { label: '可使用', color: 'text-green-500' },
      2: { label: '已用完', color: 'text-gray-400' },
      3: { label: '已过期', color: 'text-red-500' },
    }
    return map[status || 1] || { label: '未知', color: 'text-gray-400' }
  }

  // 格式化兑换码
  const formatCode = (code?: string) => {
    if (!code) return ''
    return code.split('-').join(' ')
  }

  // 删除礼品卡
  const handleDelete = (id?: number) => {
    Taro.showModal({
      title: '提示',
      content: '确定删除该礼品卡记录吗？',
      success: (res) => {
        if (res.confirm) {
          setCards(prev => prev.filter(card => card.cardId !== id && card.id !== id))
          Taro.showToast({ title: '删除成功', icon: 'success' })
        }
      }
    })
  }

  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'>
      <ScrollView scrollY style={{ height: scrollHeight }}>
        {/* 总余额 */}
        <View className='p-6 text-white' style={{ background: 'linear-gradient(to right, #c084fc, #f472b6)' }}>
          <Text className='text-sm opacity-80 block mb-2'>礼品卡总余额</Text>
          <Text className='text-4xl font-bold block mb-3'>¥{balance.toFixed(2)}</Text>
          <View className='flex gap-4'>
            <View className='rounded-lg px-3 py-1' style={{ backgroundColor: 'rgba(255,255,255,0.2)' }}>
              <Text className='text-xs text-white'>
                共 {cards.filter(c => c.status === 1).length} 张可用
              </Text>
            </View>
            <View
              className='rounded-lg px-3 py-1'
              style={{ backgroundColor: 'rgba(255,255,255,0.2)' }}
              onClick={() => Taro.navigateTo({ url: '/pages/gift-card/exchange' })}
            >
              <Text className='text-xs text-white'>兑换新卡 〉</Text>
            </View>
          </View>
        </View>

        {/* 礼品卡列表 */}
        <View className='p-3'>
          <Text className='text-sm text-gray-500 mb-2 block px-1'>礼品卡明细</Text>

          {cards.length === 0 ? (
            <View className='text-center py-16'>
              <Text className='text-4xl mb-3 block'>🎁</Text>
              <Text className='text-sm text-gray-400 mb-3 block'>暂无礼品卡</Text>
              <View
                className='inline-block bg-purple-500 text-white px-4 py-2 rounded-full'
                onClick={() => Taro.navigateTo({ url: '/pages/gift-card/purchase' })}
              >
                <Text className='text-sm'>去购买</Text>
              </View>
            </View>
          ) : (
            cards.map(card => {
              const cardId = card.cardId || card.id
              const statusInfo = getStatusLabel(card.status)
              return (
                <View key={cardId} className='bg-white rounded-xl p-4 mb-3 shadow-sm'>
                  {/* 顶部状态 */}
                  <View className='flex justify-between items-center mb-3'>
                    <Text className={`text-xs font-medium ${statusInfo.color}`}>
                      {statusInfo.label}
                    </Text>
                    <Text className='text-xs text-gray-400'>有效期至 {card.expireDate || '永久'}</Text>
                  </View>

                  {/* 卡信息 */}
                  <View className='bg-gray-50 rounded-lg p-3 mb-3'>
                    <View className='flex justify-between items-center mb-2'>
                      <Text className='text-xs text-gray-500'>面值</Text>
                      <Text className='text-base font-bold text-gray-800'>¥{card.amount || card.faceValue || '0'}</Text>
                    </View>
                    <View className='flex justify-between items-center mb-2'>
                      <Text className='text-xs text-gray-500'>余额</Text>
                      <Text className='text-base font-bold text-purple-500'>¥{card.remainAmount || card.balance || '0'}</Text>
                    </View>
                    <View className='flex justify-between items-center'>
                      <Text className='text-xs text-gray-500'>兑换码</Text>
                      <Text className='text-xs text-gray-800 font-mono'>{formatCode(card.code)}</Text>
                    </View>
                  </View>

                  {/* 操作按钮 */}
                  <View className='flex gap-2'>
                    {card.status === 1 && (
                      <View
                        className='flex-1 text-center py-2 rounded-lg bg-purple-50'
                        onClick={() => {
                          if (card.code) {
                            Taro.setClipboardData({ data: card.code })
                            Taro.showToast({ title: '已复制到剪贴板', icon: 'none' })
                          }
                        }}
                      >
                        <Text className='text-xs text-purple-500'>复制兑换码</Text>
                      </View>
                    )}
                    <View
                      className='flex-1 text-center py-2 rounded-lg bg-gray-50'
                      onClick={() => handleDelete(cardId)}
                    >
                      <Text className='text-xs text-gray-400'>删除</Text>
                    </View>
                  </View>
                </View>
              )
            })
          )}
        </View>

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

export default GiftCardBalancePage
