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

definePageConfig({
  navigationBarTitleText: '限时秒杀',
})

const SeckillListPage: React.FC = () => {
  const [seckillList, setSeckillList] = useState<ShopSeckill[]>([])
  const [loading, setLoading] = useState(true)
  const [currentTime, setCurrentTime] = useState(Date.now())

  useEffect(() => {
    fetchSeckillList()
    // 每秒更新当前时间（用于倒计时）
    const timer = setInterval(() => {
      setCurrentTime(Date.now())
    }, 1000)
    return () => clearInterval(timer)
  }, [])

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

  const handleSeckillClick = (item: ShopSeckill) => {
    Taro.navigateTo({
      url: `/pages/shop/seckill-detail/index?seckillId=${item.id}`
    })
  }

  const getCountdown = (endTime: string) => {
    const end = new Date(endTime).getTime()
    const diff = end - currentTime
    if (diff <= 0) return '已结束'

    const hours = Math.floor(diff / (1000 * 60 * 60))
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
    const seconds = Math.floor((diff % (1000 * 60)) / 1000)

    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  }

  const getProgress = (item: ShopSeckill) => {
    if (item.stock === 0) return 100
    return Math.round((item.soldCount / (item.soldCount + item.stock)) * 100)
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      {/* 顶部倒计时横幅 */}
      <View className='bg-red-500 px-3 py-2 flex items-center justify-between'>
        <Text className='text-white text-sm font-medium'>限时秒杀</Text>
        <View className='flex items-center gap-1'>
          <Text className='text-white text-xs'>距结束</Text>
          <View className='bg-white rounded px-1 py-0'>
            <Text className='text-red-500 text-xs font-bold'>--:--:--</Text>
          </View>
        </View>
      </View>

      <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>
          ) : seckillList.length === 0 ? (
            <View className='pt-20'>
              <EmptyState text='暂无秒杀活动' />
            </View>
          ) : (
            <View className="flex flex-col" style={{ gap: '12px' }}>
              {seckillList.map(item => (
                <View
                  key={item.id}
                  className='bg-white rounded-lg p-3 flex gap-3'
                  onClick={() => handleSeckillClick(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='mt-1'>
                      <View className='bg-gray-100 rounded-full overflow-hidden' style={{ height: '6px' }}>
                        <View
                          className='rounded-full'
                          style={{
                            width: `${getProgress(item)}%`,
                            height: '100%',
                            backgroundColor: '#ff4d4f'
                          }}
                        />
                      </View>
                      <Text className='text-xs text-gray-400 block' style={{ marginTop: '2px' }}>
                        已售{getProgress(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.seckillPrice}
                        </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: item.stock > 0 ? '#ff4d4f' : '#999' }}
                      >
                        <Text>{item.stock > 0 ? '立即抢购' : '已抢光'}</Text>
                      </View>
                    </View>
                  </View>
                </View>
              ))}
            </View>
          )}
        </View>
      </ScrollView>
    </View>
  )
}

export default SeckillListPage
