import React, { useState, useEffect } from 'react'
import { View, Text, Image, ScrollView, RichText } from '@tarojs/components'
import Taro, { useRouter, useShareAppMessage } from '@tarojs/taro'
import { getShopPointsProduct } from '@/api/shop/shopPointsProduct'
import type { ShopPointsProduct } from '@/api/shop/shopPointsProduct/model'
import EmptyState from '@/components/common/EmptyState'

definePageConfig({
  navigationBarTitleText: '积分商品',
})

const PointsProductDetail: React.FC = () => {
  const router = useRouter()
  const id = Number(router.params.id)
  const [product, setProduct] = useState<ShopPointsProduct | null>(null)
  const [loading, setLoading] = useState(true)

  // 微信分享
  useShareAppMessage(() => {
    return {
      title: product?.productName || '积分商品推荐',
      path: `/pages/points/product-detail?id=${id}`,
      imageUrl: product?.productImage || ''
    }
  })

  useEffect(() => {
    if (id) {
      loadProduct()
    }
  }, [id])

  const loadProduct = async () => {
    setLoading(true)
    try {
      const data = await getShopPointsProduct(id)
      setProduct(data)
    } catch (e) {
      console.error('加载积分商品失败:', e)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const getProductTypeLabel = (type?: number) => {
    switch (type) {
      case 0: return '实物商品'
      case 1: return '优惠券'
      case 2: return '虚拟商品'
      default: return '商品'
    }
  }

  const handleExchange = () => {
    if (!product) return
    if ((product.stock || 0) <= 0) {
      Taro.showToast({ title: '商品已售罄', icon: 'none' })
      return
    }
    // 跳转兑换确认页，传递商品信息
    Taro.navigateTo({
      url: `/pages/points/exchange/index?id=${product.id}`
    })
  }

  if (loading) {
    return (
      <View className='min-h-screen bg-gray-50'>
        <View className='w-full bg-orange-50 animate-pulse' style={{ height: '375px' }} />
        <View className='bg-white p-4'>
          <View className='h-6 bg-gray-200 rounded mb-2 animate-pulse' style={{ width: '70%' }} />
          <View className='h-8 bg-gray-200 rounded mb-2 animate-pulse' style={{ width: '40%' }} />
          <View className='h-4 bg-gray-200 rounded animate-pulse' style={{ width: '55%' }} />
        </View>
      </View>
    )
  }

  if (!product) {
    return (
      <View className='min-h-screen bg-gray-50'>
        <EmptyState icon='🎁' text='商品不存在或已下架' />
      </View>
    )
  }

  const isSoldOut = (product.stock || 0) <= 0

  return (
    <View className='min-h-screen bg-gray-50 flex flex-col'>
      <ScrollView scrollY className='flex-1'>
        {/* 商品图片 */}
        {product.productImage ? (
          <Image
            className='w-full'
            style={{ height: '375px' }}
            src={product.productImage}
            mode='aspectFill'
            onClick={() => Taro.previewImage({ current: product.productImage, urls: [product.productImage!] })}
          />
        ) : (
          <View className='w-full bg-orange-50 flex items-center justify-center' style={{ height: '375px' }}>
            <Text className='text-gray-400 text-sm'>暂无图片</Text>
          </View>
        )}

        {/* 价格与基本信息 */}
        <View className='bg-white p-4'>
          <View className='flex items-center gap-2 mb-2'>
            <View className='px-2 rounded' style={{ backgroundColor: '#fff7ed', paddingTop: '2px', paddingBottom: '2px' }}>
              <Text className='text-xs text-orange-500'>{getProductTypeLabel(product.productType)}</Text>
            </View>
            {product.isHot === 1 && (
              <View className='px-2 rounded' style={{ backgroundColor: '#fef2f2', paddingTop: '2px', paddingBottom: '2px' }}>
                <Text className='text-xs text-red-500'>热门</Text>
              </View>
            )}
          </View>
          <Text className='text-base font-bold text-gray-800 block leading-tight'>
            {product.productName || '积分商品'}
          </Text>
          <View className='flex items-baseline gap-1 mt-2'>
            <Text className='text-xs text-orange-500'>需</Text>
            <Text className='text-2xl font-bold text-orange-500'>
              {product.pointsPrice || 0}
            </Text>
            <Text className='text-xs text-orange-500'>积分</Text>
            {Number(product.moneyPrice) > 0 && (
              <>
                <Text className='text-xs text-gray-500 ml-1'>+</Text>
                <Text className='text-base font-medium text-orange-500 ml-1'>
                  {'\u00A5'}{product.moneyPrice}
                </Text>
              </>
            )}
          </View>
          <View className='flex items-center gap-4 mt-2'>
            <Text className='text-xs text-gray-400'>
              已兑换 {product.sales || 0} 件
            </Text>
            <Text className={`text-xs ${isSoldOut ? 'text-red-400' : 'text-green-500'}`}>
              {isSoldOut ? '已售罄' : `剩余 ${product.stock || 0} 件`}
            </Text>
          </View>
        </View>

        {/* 商品描述 */}
        {product.description && (
          <View className='bg-white mt-2 p-4'>
            <Text className='text-sm font-medium text-gray-800 block mb-3'>商品介绍</Text>
            <RichText
              className='text-sm text-gray-600 leading-relaxed'
              nodes={product.description}
            />
          </View>
        )}

        {/* 底部占位，防止被固定栏遮挡 */}
        <View style={{ height: '80px' }} />
      </ScrollView>

      {/* 底部兑换按钮 */}
      <View className='bg-white border-t border-gray-100 px-4 py-3 flex items-center justify-center' style={{ paddingBottom: '20px' }}>
        <View
          className='w-full py-3 rounded-full text-center text-white font-medium'
          style={{ backgroundColor: isSoldOut ? '#d1d5db' : '#f97316' }}
          onClick={handleExchange}
        >
          <Text className='text-sm'>{isSoldOut ? '已售罄' : '立即兑换'}</Text>
        </View>
      </View>
    </View>
  )
}

export default PointsProductDetail
