import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { pageShopEvent, getEventStatusLabel } from '@/api/shop/shopEvent'
import type { ShopEvent } from '@/api/shop/shopEvent'
import EmptyState from '@/components/common/EmptyState'
import LoadMore from '@/components/common/LoadMore'

definePageConfig({ navigationBarTitleText: '赛事报名' })

const TABS = ['全部', '未开始', '报名中', '已截止', '已结束']
const STATUS_MAP: Record<number, number | undefined> = { 1: 0, 2: 1, 3: 2, 4: 3 }

const EventListPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState(0)
  const [events, setEvents] = useState<ShopEvent[]>([])
  const [loading, setLoading] = useState(false)
  const [finished, setFinished] = useState(false)
  const [page, setPage] = useState(1)

  useEffect(() => {
    setEvents([])
    setPage(1)
    setFinished(false)
    loadList(1)
  }, [activeTab])

  const loadList = async (p: number) => {
    if (loading) return
    setLoading(true)
    try {
      const res = await pageShopEvent({
        page: p,
        limit: 10,
        status: STATUS_MAP[activeTab],
      })
      if (res?.list) {
        setEvents(prev => p === 1 ? res.list : [...prev, ...res.list])
        setFinished(res.list.length < 10)
        setPage(p)
      }
    } catch (err) {
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const formatDate = (dateStr: string) => {
    const d = new Date(dateStr)
    return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      {/* Tab 栏 */}
      <View className='bg-white flex'>
        {TABS.map((tab, index) => (
          <View
            key={index}
            className={`flex-1 text-center py-3 relative ${activeTab === index ? 'text-orange-500 font-medium' : 'text-gray-600'}`}
            onClick={() => setActiveTab(index)}
          >
            <Text className='text-sm'>{tab}</Text>
            {activeTab === index && (
              <View className='absolute bottom-0 w-8 h-px bg-orange-500 rounded' style={{ left: '50%', transform: 'translateX(-50%)' }} />
            )}
          </View>
        ))}
      </View>

      <ScrollView scrollY className='flex-1' onScrollToLower={() => !finished && !loading && loadList(page + 1)} lowerThreshold={100}>
        <View className='p-3'>
          {events.length === 0 && !loading ? (
            <EmptyState text='暂无赛事' />
          ) : (
            events.map(event => {
              const statusInfo = getEventStatusLabel(event.status as number)
              return (
                <View
                  key={event.id}
                  className='bg-white rounded-xl mb-3 shadow-sm overflow-hidden'
                  onClick={() => Taro.navigateTo({ url: `/pages/event/detail/index?id=${event.id}` })}
                >
                  {/* 封面 */}
                  {event.image ? (
                    <Image src={event.image} className='w-full' style={{ height: '160px' }} mode='aspectFill' />
                  ) : (
                    <View className='w-full flex items-center justify-center' style={{ height: '140px', background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }}>
                      <Text className='text-5xl'>🏆</Text>
                    </View>
                  )}

                  <View className='p-4'>
                    {/* 标题+状态 */}
                    <View className='flex items-center gap-2 mb-2'>
                      <Text className='text-base font-bold text-gray-800 flex-1'>{event.name}</Text>
                      <View className={`px-2 py-1 rounded ${event.status === 1 ? 'bg-green-50' : event.status === 0 ? 'bg-blue-50' : 'bg-gray-50'}`}>
                        <Text className={`text-xs ${statusInfo.color}`}>{statusInfo.label}</Text>
                      </View>
                      {event.isHot === 1 && (
                        <View className='bg-red-50 px-2 py-1 rounded'>
                          <Text className='text-xs text-red-500'>🔥热门</Text>
                        </View>
                      )}
                    </View>

                    {/* 信息行 */}
                    <View className='flex items-center gap-3 text-xs text-gray-500 mb-3'>
                      <Text>📅 {formatDate(event.eventDate)}</Text>
                      {event.location && <Text>📍 {event.location}</Text>}
                    </View>

                    {/* 底部：名额+费用+按钮 */}
                    <View className='flex items-center justify-between'>
                      <View className='flex items-center gap-3 text-xs text-gray-500'>
                        <Text>👥 {event.paidCount}/{event.maxParticipants > 0 ? event.maxParticipants : '不限'}</Text>
                        <Text className={event.entryFee > 0 ? 'text-orange-500 font-medium' : 'text-green-500'}>
                          {event.entryFee > 0 ? `¥${event.entryFee}` : '免费'}
                        </Text>
                      </View>
                      {event.status === 1 && (
                        event.maxParticipants > 0 && event.paidCount >= event.maxParticipants ? (
                          <View className='bg-gray-200 px-4 py-1 rounded-full'>
                            <Text className='text-xs text-gray-500'>名额已满</Text>
                          </View>
                        ) : (
                          <View className='bg-orange-500 px-4 py-1 rounded-full'>
                            <Text className='text-xs text-white font-medium'>立即报名</Text>
                          </View>
                        )
                      )}
                    </View>
                  </View>
                </View>
              )
            })
          )}
          <LoadMore loading={loading} finished={finished} />
        </View>
      </ScrollView>
    </View>
  )
}

export default EventListPage
