import { Text, View } from '@tarojs/components'
import Taro, { useDidShow, useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { backend, type BackendEventRegistration } from '@/api/backend'
import { ConfirmDrawer, MetaRow, Page } from '@/components/ui'
import { ensureStaffLoggedIn } from '@/stores/storage'

function memberLabel(level?: BackendEventRegistration['membershipLevel']) {
  if (level === 'senior') return '高级会员'
  if (level === 'junior') return '初级会员'
  return '注册用户'
}

function statusLabel(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 formatTime(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')}`
}

export default function CheckinRegistrationDetailPage() {
  const [id, setId] = useState('')
  const [eventId, setEventId] = useState('')
  const [item, setItem] = useState<BackendEventRegistration | null>(null)
  const [showConfirm, setShowConfirm] = useState(false)

  async function loadDetail(currentId = id) {
    const token = ensureStaffLoggedIn('/pages/checkin/events/index')
    if (!token) {
      return
    }
    if (!currentId) return
    try {
      setItem(await backend.staffEventRegistration(token, currentId))
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '详情加载失败', icon: 'none' })
    }
  }

  function requestManualCheckin() {
    const token = ensureStaffLoggedIn('/pages/checkin/events/index')
    if (!token) return
    if (!item?.id) return
    if (item.status === 'checked_in') {
      Taro.showToast({ title: '该报名人已核销', icon: 'none' })
      return
    }
    if (item.status !== 'registered') {
      Taro.showToast({ title: '当前状态不可核销', icon: 'none' })
      return
    }
    setShowConfirm(true)
  }

  async function manualCheckin() {
    const token = ensureStaffLoggedIn('/pages/checkin/events/index')
    if (!token) return
    if (!item?.id) return
    setShowConfirm(false)
    try {
      const result = await backend.staffCheckinManualUnified(token, {
        kind: 'event',
        productId: eventId,
        registrationId: item.id,
        source: 'miniapp_manual'
      })
      setItem(result.registration as BackendEventRegistration)
      Taro.showToast({ title: result.alreadyCheckedIn ? '已核销过' : '核销成功', icon: 'success' })
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '核销失败', icon: 'none' })
    }
  }

  useLoad((query) => {
    const nextId = String(query.id || '')
    setId(nextId)
    setEventId(String(query.eventId || ''))
    void loadDetail(nextId)
  })

  useDidShow(() => {
    if (id) void loadDetail(id)
  })

  return (
    <Page title="报名人详情" subtle={item?.event?.title || ''}>
      <View className="checkin-detail-head">
        <View>
          <Text className="checkin-detail-name">{item?.userName || '未填写姓名'}</Text>
          <Text className="checkin-detail-meta">{item?.userPhone || '-'} · {memberLabel(item?.membershipLevel)}</Text>
        </View>
        <View className={item?.status === 'checked_in' ? 'checkin-manual done' : 'checkin-manual'} onClick={requestManualCheckin}>
          {item?.status === 'checked_in' ? '已核销' : item?.status && item.status !== 'registered' ? statusLabel(item.status) : '确认核销'}
        </View>
      </View>

      <View className="checkin-info">
        <MetaRow label="核销状态" value={statusLabel(item?.status)} />
        <MetaRow label="组织单位" value={item?.userOrganization || '-'} />
        <MetaRow label="活动名称" value={item?.event?.title || '-'} />
        <MetaRow label="活动地点" value={item?.event?.location || '-'} />
        <MetaRow label="订单号" value={item?.orderNo || '-'} />
        <MetaRow label="核销码" value={item?.checkinCode || '-'} />
        <MetaRow label="报名时间" value={formatTime(item?.createdAt)} />
        <MetaRow label="核销时间" value={formatTime(item?.checkedInAt)} />
        <MetaRow label="核销人员" value={item?.checkedInByStaffName || '-'} />
      </View>
      {showConfirm && (
        <ConfirmDrawer
          title="确认核销"
          content={`确认将 ${item?.userName || item?.userPhone || '该报名人'} 标记为已核销？`}
          confirmText="确认核销"
          onCancel={() => setShowConfirm(false)}
          onConfirm={() => void manualCheckin()}
        />
      )}
    </Page>
  )
}
