import { Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import { backend, type BackendEventRegistration } from '@/api/backend'
import { EmptyState, Page, ProductImage, Section, StatusSide } from '@/components/ui'
import { ensureLoggedIn, getToken } from '@/stores/storage'

function eventTime(value?: string | null) {
  if (!value) return '时间待定'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '时间待定'
  return `${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

function eventStatusLabel(status: BackendEventRegistration['status']) {
  if (status === 'pending_payment') return '待支付'
  if (status === 'waitlisted') return '候补中'
  if (status === 'checked_in') return '已核销'
  if (status === 'cancel_requested') return '取消处理中'
  if (status === 'cancelled') return '已取消'
  if (status === 'no_show') return '未到场'
  if (status === 'refunded') return '已关闭'
  return '已报名'
}

function eventGroup(item: BackendEventRegistration) {
  if (item.status === 'pending_payment') return '待支付'
  if (item.status === 'waitlisted') return '候补中'
  if (item.status === 'checked_in') return '已核销'
  if (['cancel_requested', 'cancelled', 'no_show', 'refunded'].includes(item.status)) return '已关闭'
  const end = item.event?.endsAt || item.event?.startsAt
  if (end && new Date(end).getTime() < Date.now()) return '已结束'
  return '已报名'
}

export default function EventsPage() {
  const [items, setItems] = useState<BackendEventRegistration[]>([])
  const [loading, setLoading] = useState(false)
  const groups = ['待支付', '已报名', '候补中', '已核销', '已结束', '已关闭']

  useDidShow(() => {
    const user = ensureLoggedIn('/pages/account/events/index')
    const token = getToken()
    if (!user || !token) return
    setLoading(true)
    backend.accountEventRegistrations(token)
      .then((result) => setItems(result.items))
      .catch((error) => Taro.showToast({ title: error instanceof Error ? error.message : '活动加载失败', icon: 'none' }))
      .finally(() => setLoading(false))
  })

  return (
    <Page title="报名活动" subtle={loading ? '正在同步报名记录' : `当前 ${items.length} 场`}>
      {!items.length && !loading ? <EmptyState title="暂无报名活动" text="报名活动后，会在这里查看核销码和报名状态。" /> : groups.map((group) => {
        const groupItems = items.filter((item) => eventGroup(item) === group)
        if (!groupItems.length) return null
        return (
          <Section key={group} title={group}>
            <View className="list-shell">
            {groupItems.map((item) => (
              <View key={`${group}-${item.id}`} className="list-line" onClick={() => Taro.navigateTo({ url: `/pages/account/events/detail/index?id=${encodeURIComponent(item.id)}` })}>
                <View className="list-main" style={{ display: 'flex', gap: '18px' }}>
                  <ProductImage className="service-thumb" src={item.event?.coverUrl || 'event'} />
                  <View style={{ flex: 1 }}>
                    <Text className="row-title">{item.event?.title || '活动'}</Text>
                    <Text className="row-sub">{eventTime(item.event?.startsAt)} · {item.event?.isOnline ? '线上活动' : item.event?.location || '地点待定'} · {eventStatusLabel(item.status)}</Text>
                  </View>
                </View>
                <StatusSide value={eventStatusLabel(item.status)} orange={item.status === 'pending_payment' || item.status === 'waitlisted'} />
              </View>
            ))}
            </View>
          </Section>
        )
      })}
    </Page>
  )
}
