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

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

const PointsProductListPage: React.FC = () => {
  const [products, setProducts] = useState<ShopPointsProduct[]>([])
  const [loading, setLoading] = useState(false)
  const [loadingMore, setLoadingMore] = useState(false)
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const limit = 20

  useEffect(() => {
    loadProducts(true)
  }, [])

  const loadProducts = async (reset = false) => {
    const currentPage = reset ? 1 : page
    if (reset) {
      setLoading(true)
    } else {
      setLoadingMore(true)
    }

    try {
      const data = await pageShopPointsProduct({
        page: currentPage,
        limit,
        status: 1,
      })

      if (reset) {
        setProducts(data?.list || [])
      } else {
        setProducts(prev => [...prev, ...(data?.list || [])])
      }
      setHasMore((data?.list || []).length >= limit)
      setPage(currentPage + 1)
    } catch (e) {
      console.error('加载积分商品失败:', e)
    } finally {
      setLoading(false)
      setLoadingMore(false)
    }
  }

  const handleLoadMore = () => {
    if (!loadingMore && hasMore) {
      loadProducts(false)
    }
  }

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

  return (
    <View className='min-h-screen bg-gray-50'>
      {loading ? (
        <View className='p-3'>
          <View className='grid grid-cols-2 gap-2'>
            {Array.from({ length: 6 }).map((_, i) => (
              <View key={i} className='bg-white rounded-lg overflow-hidden animate-pulse'>
                <View className='w-full aspect-square bg-gray-200' />
                <View className='p-2'>
                  <View className='h-4 bg-gray-200 rounded mb-2' style={{ width: '75%' }} />
                  <View className='h-3 bg-gray-200 rounded' style={{ width: '50%' }} />
                </View>
              </View>
            ))}
          </View>
        </View>
      ) : products.length === 0 ? (
        <EmptyState
          icon='🎁'
          text='暂无积分商品'
          subText='平台正在准备更多好物，敬请期待'
        />
      ) : (
        <ScrollView
          scrollY
          className='flex-1'
          onScrollToLower={handleLoadMore}
        >
          <View className='p-3'>
            <View className='grid grid-cols-2 gap-2'>
              {products.map(product => (
                <View
                  key={product.id}
                  className='bg-white rounded-lg overflow-hidden'
                  onClick={() => Taro.navigateTo({ url: `/pages/points/product-detail?id=${product.id}` })}
                >
                  <View className='w-full aspect-square bg-orange-50 relative'>
                    <Image
                      className='w-full h-full'
                      src={product.productImage || ''}
                      mode='aspectFill'
                    />
                    <View className='absolute top-1 right-1 px-2 rounded-full bg-black bg-opacity-50' style={{ paddingTop: '2px', paddingBottom: '2px' }}>
                      <Text className='text-white text-xs'>{getProductTypeLabel(product.productType)}</Text>
                    </View>
                    {product.isHot === 1 && (
                      <View className='absolute top-1 left-1 px-2 rounded-br-lg' style={{ backgroundColor: '#f97316', paddingTop: '2px', paddingBottom: '2px' }}>
                        <Text className='text-white text-xs'>热门</Text>
                      </View>
                    )}
                    {product.stock === 0 && (
                      <View className='absolute inset-0 bg-black bg-opacity-40 flex items-center justify-center'>
                        <Text className='text-white font-medium'>已售罄</Text>
                      </View>
                    )}
                  </View>
                  <View className='p-2'>
                    <Text className='text-sm text-gray-700 line-clamp-2 block'>
                      {product.productName || '积分商品'}
                    </Text>
                    <View className='flex items-center gap-1 mt-1'>
                      <Text className='text-base 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-400 ml-1'>
                          +¥{product.moneyPrice}
                        </Text>
                      )}
                    </View>
                    <View className='flex justify-between items-center mt-1'>
                      <Text className='text-xs text-gray-400'>
                        已兑换 {product.sales || 0}
                      </Text>
                      <Text className={`text-xs ${(product.stock || 0) > 0 ? 'text-green-500' : 'text-gray-400'}`}>
                        库存 {product.stock || 0}
                      </Text>
                    </View>
                  </View>
                </View>
              ))}
            </View>

            {/* 加载更多 */}
            {hasMore && (
              <LoadMore loading={loadingMore} />
            )}
            {!hasMore && products.length > 0 && (
              <View className='py-6 text-center'>
                <Text className='text-xs text-gray-400'>— 没有更多了 —</Text>
              </View>
            )}
          </View>
        </ScrollView>
      )}
    </View>
  )
}

export default PointsProductListPage
