import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { getShopEvent, getRegistrationStatus, getEventStatusLabel } from '@/api/shop/shopEvent'
import type { ShopEvent, RegistrationStatus, EventFormField } from '@/api/shop/shopEvent'

definePageConfig({ navigationBarTitleText: '赛事详情' })

const EventDetailPage: React.FC = () => {
  const { id } = Taro.getCurrentInstance().router?.params || {}
  const [event, setEvent] = useState<ShopEvent | null>(null)
  const [regStatus, setRegStatus] = useState<RegistrationStatus | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (id) {
      fetchDetail(Number(id))
      fetchRegStatus(Number(id))
    }
  }, [id])

  const fetchDetail = async (eventId: number) => {
    try {
      const data = await getShopEvent(eventId)
      setEvent(data)
    } catch (err: any) {
      Taro.showToast({ title: err.message || '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const fetchRegStatus = async (eventId: number) => {
    try {
      const data = await getRegistrationStatus(eventId)
      setRegStatus(data)
    } catch {
      // 未登录时忽略
    }
  }

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

  const handleRegister = () => {
    if (!event) return
    Taro.navigateTo({ url: `/pages/event/register/index?id=${event.id}` })
  }

  if (loading) {
    return (
      <View className='min-h-screen bg-gray-50 flex items-center justify-center'>
        <Text className='text-sm text-gray-400'>加载中...</Text>
      </View>
    )
  }

  if (!event) {
    return (
      <View className='min-h-screen bg-gray-50 flex items-center justify-center'>
        <Text className='text-sm text-gray-400'>赛事不存在</Text>
      </View>
    )
  }

  const statusInfo = getEventStatusLabel(event.status as number)
  const isFull = event.maxParticipants > 0 && event.paidCount >= event.maxParticipants
  const alreadyPaid = regStatus?.registered && regStatus.payStatus === 1
  const pendingPay = regStatus?.registered && regStatus.payStatus === 0

  // 解析动态表单字段
  let formFields: EventFormField[] = []
  if (event.formFields) {
    if (Array.isArray(event.formFields)) {
      formFields = event.formFields
    } else {
      try { formFields = JSON.parse(event.formFields) } catch { formFields = [] }
    }
  }

  return (
    <View className='min-h-screen bg-gray-50 flex flex-col'>
      <ScrollView scrollY className='flex-1'>
        {/* 封面 */}
        {event.image ? (
          <Image src={event.image} className='w-full' style={{ height: '200px' }} mode='aspectFill' />
        ) : (
          <View className='w-full flex items-center justify-center' style={{ height: '200px', background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }}>
            <Text className='text-6xl'>🏆</Text>
          </View>
        )}

        {/* 基本信息 */}
        <View className='bg-white p-4 mb-3'>
          <View className='flex items-center gap-2 mb-3'>
            <Text className='text-xl font-bold text-gray-800 flex-1'>{event.name}</Text>
            <View className={`px-2 py-1 rounded ${event.status === 1 ? 'bg-green-50' : 'bg-gray-50'}`}>
              <Text className={`text-xs ${statusInfo.color}`}>{statusInfo.label}</Text>
            </View>
          </View>

          <View className='space-y-2 text-sm text-gray-600'>
            <View className='flex items-center gap-2'>
              <Text className='text-gray-400 w-16'>赛事时间</Text>
              <Text>{formatDate(event.eventDate)}</Text>
            </View>
            {event.location && (
              <View className='flex items-center gap-2'>
                <Text className='text-gray-400 w-16'>赛事地点</Text>
                <Text>{event.location}</Text>
              </View>
            )}
            <View className='flex items-center gap-2'>
              <Text className='text-gray-400 w-16'>报名名额</Text>
              <Text>{event.paidCount} / {event.maxParticipants > 0 ? event.maxParticipants : '不限'}</Text>
              {isFull && <Text className='text-red-500 text-xs'>（已满）</Text>}
            </View>
            <View className='flex items-center gap-2'>
              <Text className='text-gray-400 w-16'>报名费用</Text>
              <Text className={event.entryFee > 0 ? 'text-orange-500 font-bold text-base' : 'text-green-500 font-bold'}>
                {event.entryFee > 0 ? `¥${event.entryFee}` : '免费'}
              </Text>
            </View>
          </View>
        </View>

        {/* 报名须知 */}
        <View className='bg-white p-4 mb-3'>
          <Text className='text-base font-medium text-gray-800 mb-2 block'>报名须知</Text>
          <View className='text-xs text-gray-500 space-y-1'>
            {formFields.length > 0 ? (
              formFields.map(field => (
                <Text key={field.key} className='block'>
                  • 需{field.required === 1 ? '填写' : '选填'}{field.label}
                  {field.type === 'select' || field.type === 'radio' ? `（${(field.options || []).join('/')}）` : ''}
                </Text>
              ))
            ) : (
              <Text className='block'>• 该赛事无需填写额外信息</Text>
            )}
            {event.entryFee > 0 && <Text className='block'>• 缴费成功后报名生效，缴费失败不占名额</Text>}
          </View>
        </View>

        {/* 赛事描述 */}
        {event.description && (
          <View className='bg-white p-4 mb-3'>
            <Text className='text-base font-medium text-gray-800 mb-2 block'>赛事详情</Text>
            <Text className='text-sm text-gray-700 leading-7 whitespace-pre-wrap block'>{event.description}</Text>
          </View>
        )}

        <View className='h-24' />
      </ScrollView>

      {/* 底部操作栏 */}
      <View className='bg-white px-4 py-3 shadow-lg' style={{ paddingBottom: '20px' }}>
        {alreadyPaid && (
          <View className='bg-green-500 text-center py-3 rounded-full'>
            <Text className='text-sm text-white font-bold'>✓ 已报名</Text>
          </View>
        )}
        {pendingPay && (
          <View
            className='bg-orange-500 text-center py-3 rounded-full'
            onClick={() => Taro.navigateTo({ url: '/pages/event/my/index' })}
          >
            <Text className='text-sm text-white font-bold'>待缴费 — 前往我的报名</Text>
          </View>
        )}
        {!regStatus?.registered && event.status === 1 && !isFull && (
          <View className='bg-orange-500 text-center py-3 rounded-full' onClick={handleRegister}>
            <Text className='text-sm text-white font-bold'>
              {event.entryFee > 0 ? `立即报名 ¥${event.entryFee}` : '立即报名（免费）'}
            </Text>
          </View>
        )}
        {!regStatus?.registered && event.status === 1 && isFull && (
          <View className='bg-gray-300 text-center py-3 rounded-full'>
            <Text className='text-sm text-white font-bold'>名额已满</Text>
          </View>
        )}
        {event.status !== 1 && !alreadyPaid && !pendingPay && (
          <View className='bg-gray-300 text-center py-3 rounded-full'>
            <Text className='text-sm text-white font-bold'>{statusInfo.label}</Text>
          </View>
        )}
      </View>
    </View>
  )
}

export default EventDetailPage
