import { Text, View } from '@tarojs/components'
import { useLoad } from '@tarojs/taro'
import { useMemo, useState } from 'react'
import Taro from '@tarojs/taro'
import { backend, type BackendEventRegistration } from '@/api/backend'
import { MetaRow, Page, ProductImage } from '@/components/ui'
import { ensureLoggedIn, getToken } from '@/stores/storage'
import { createQrMatrix } from '@/utils/qr-code'

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 fullTime(value?: string | null) {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '-'
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${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 CheckinQr({ value }: { value: string }) {
  const matrix = useMemo(() => createQrMatrix(value || 'NO-CHECKIN'), [value])
  const cellSize = `${100 / matrix.length}%`
  return (
    <View className="checkin-qr-grid">
      {matrix.flatMap((row, y) => row.map((dark, x) => (
        <View key={`${x}-${y}`} className={dark ? 'checkin-qr-cell dark' : 'checkin-qr-cell'} style={{ width: cellSize, height: cellSize }} />
      )))}
    </View>
  )
}

export default function EventDetailPage() {
  const [item, setItem] = useState<BackendEventRegistration | null>(null)
  useLoad((query) => {
    const id = String(query.id || '')
    const user = ensureLoggedIn(`/pages/account/events/detail/index?id=${encodeURIComponent(id)}`)
    const token = getToken()
    if (!user || !token || !id) return
    backend.accountEventRegistration(token, id)
      .then(setItem)
      .catch((error) => Taro.showToast({ title: error instanceof Error ? error.message : '活动加载失败', icon: 'none' }))
  })

  function copyOnlineUrl(value: string) {
    void Taro.setClipboardData({ data: value })
    Taro.showToast({ title: '活动入口已复制', icon: 'none' })
  }

  if (!item) {
    return (
      <Page title="活动详情">
        <View className="panel panel-pad">
          <Text className="row-sub">正在同步报名信息。</Text>
        </View>
      </Page>
    )
  }

  const event = item.event
  const status = eventStatusLabel(item.status)
  const canShowQr = item.status === 'registered' && Boolean(item.checkinCode)
  const canOpenOnline = event.isOnline && event.onlineUrl && ['registered', 'checked_in'].includes(item.status)
  const unavailable = event.status === 'offline' || event.status === 'deleted' || event.productStatus === 'offline'

  return (
    <Page title={event.title} subtle={status}>
      <View className="event-pass-shell">
        <ProductImage className="event-pass-cover" src={event.coverUrl || 'event'} label={event.coverLabel || '活动'} />
        <View className="event-pass-main">
          <View className="event-pass-heading">
            <Text className="event-pass-title">{event.title}</Text>
            {unavailable && <Text className="event-pass-offline">已下架</Text>}
          </View>
          <Text className="event-pass-summary">{event.summary}</Text>

          <View className="course-facts">
            <MetaRow label="时间" value={`${eventTime(event.startsAt)}${event.endsAt ? ` - ${eventTime(event.endsAt)}` : ''}`} />
            <MetaRow label="地点" value={event.isOnline ? '线上活动' : event.location || '-'} />
            <MetaRow label="形式" value={event.eventFormat || '-'} />
            <MetaRow label="订单号" value={item.orderNo || '-'} />
          </View>

          <View className="checkin-pass-card event-pass-card">
            <View className="checkin-pass-copy">
              <Text className="checkin-pass-label">活动通行证</Text>
              <Text className="checkin-pass-title">{status}</Text>
              <Text className="checkin-pass-text">
                {canShowQr ? '到场签到或线上核销时出示此码。' : item.status === 'pending_payment' ? '完成支付后会生成有效核销凭证。' : '当前状态不需要出示核销二维码。'}
              </Text>
              <MetaRow label="核销码" value={item.checkinCode || '-'} />
              <MetaRow label="报名时间" value={fullTime(item.createdAt)} />
              <MetaRow label="核销时间" value={fullTime(item.checkedInAt)} />
              <MetaRow label="核销人员" value={item.checkedInByStaffName || '-'} />
            </View>
            <View className="checkin-pass-qr">
              {canShowQr ? <CheckinQr value={item.checkinCode} /> : <Text className="checkin-pass-state">{status}</Text>}
            </View>
          </View>

          {canOpenOnline && (
            <View className="primary-btn course-inline-btn" onClick={() => copyOnlineUrl(event.onlineUrl || '')}>复制线上活动入口</View>
          )}

          {item.status === 'pending_payment' && item.orderNo && (
            <View className="primary-btn course-inline-btn" onClick={() => Taro.navigateTo({ url: `/pages/account/orders/detail/index?id=${encodeURIComponent(item.orderNo || '')}` })}>查看订单</View>
          )}
        </View>
      </View>
    </Page>
  )
}
