import React, { useEffect, useState } from 'react'
import { View, Text, Image, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { pageShopGroupBuy } from '@/api/shop/shopGroupBuy'
import type { ShopGroupBuy } from '@/api/shop/shopGroupBuy/model'
import EmptyState from '@/components/common/EmptyState'

definePageConfig({
  navigationBarTitleText: '拼团活动',
})

const GroupBuyListPage: React.FC = () => {
  const [groupBuyList, setGroupBuyList] = useState<ShopGroupBuy[]>([])
  const [loading, setLoading] = useState(true)

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

  const fetchGroupBuyList = async () => {
    try {
      setLoading(true)
      const res = await pageShopGroupBuy({ page: 1, pageSize: 20, status: 1 })
      if (res.code === 0 && res.data) {
        setGroupBuyList(res.data.items || [])
      }
    } catch (err) {
      console.error('获取拼团列表失败', err)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const handleGroupBuyClick = (item: ShopGroupBuy) => {
    Taro.navigateTo({
      url: `/pages/shop/group-buy-detail/index?groupBuyId=${item.id}`
    })
  }

  const getStatusText = (item: ShopGroupBuy) => {
    const remaining = item.groupSize - item.currentSize
    if (remaining <= 0) return '已满员'
    return `还差${remaining}人成团`
  }

  const getStatusColor = (item: ShopGroupBuy) => {
    const remaining = item.groupSize - item.currentSize
    if (remaining <= 0) return '#999'
    return '#ff4d4f'
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      <ScrollView scrollY className='h-screen'>
        <View className='p-3'>
          {loading ? (
            <View className='flex items-center justify-center py-20'>
              <Text className='text-gray-400 text-sm'>加载中...</Text>
            </View>
          ) : groupBuyList.length === 0 ? (
            <View className='pt-20'>
              <EmptyState text='暂无拼团活动' />
            </View>
          ) : (
            <View className="flex flex-col" style={{ gap: '12px' }}>
              {groupBuyList.map(item => (
                <View
                  key={item.id}
                  className='bg-white rounded-lg p-3 flex gap-3'
                  onClick={() => handleGroupBuyClick(item)}
                >
                  <Image
                    className='w-24 h-24 rounded-md bg-gray-100 flex-shrink-0'
                    src={item.goodsImage || item.product?.image || ''}
                    mode='aspectFill'
                  />
                  <View className='flex-1 flex flex-col justify-between'>
                    <Text className='text-sm text-gray-700 font-medium line-clamp-2'>
                      {item.goodsName || item.product?.name || '商品名称'}
                    </Text>

                    <View className='flex items-center gap-2 mt-1'>
                      <View className='bg-red-50 px-2 py-1 rounded'>
                        <Text className='text-xs text-red-500'>{item.groupSize}人团</Text>
                      </View>
                      <Text className='text-xs' style={{ color: getStatusColor(item) }}>
                        {getStatusText(item)}
                      </Text>
                    </View>

                    <View className='flex items-center justify-between mt-1'>
                      <View className='flex items-baseline gap-1'>
                        <Text className='text-lg font-bold text-red-500'>
                          {'\u00A5'}{item.groupPrice}
                        </Text>
                        <Text className='text-xs text-gray-400 line-through'>
                          {'\u00A5'}{item.product?.price || 0}
                        </Text>
                      </View>
                      <View
                        className='px-3 py-1 rounded-full text-white text-xs'
                        style={{ backgroundColor: '#ff4d4f' }}
                      >
                        <Text>去拼团</Text>
                      </View>
                    </View>
                  </View>
                </View>
              ))}
            </View>
          )}
        </View>
      </ScrollView>
    </View>
  )
}

export default GroupBuyListPage
