import { Button, Input, Text, View } from '@tarojs/components'
import Taro, { useDidShow, useLoad } from '@tarojs/taro'
import { useMemo, useState } from 'react'
import { backend, type BackendEventProduct, type BackendEventRegistration } from '@/api/backend'
import { 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 checkinErrorMessage(error: unknown) {
  const code = error instanceof Error ? (error as Error & { code?: string }).code || error.message : ''
  if (code.includes('not_found')) return '未找到报名记录'
  if (code.includes('mismatch')) return '不属于当前活动'
  if (code.includes('status_not_allowed')) return '当前状态不可核销'
  if (code.includes('empty_checkin_code')) return '核销码为空'
  return error instanceof Error ? error.message : '核销失败'
}

function extractPassportNo(value: string) {
  const text = String(value || '').trim().toUpperCase()
  const match = text.match(/[A-Z]{5}-?\d{5}/)
  if (!match) return ''
  const compact = match[0].replace('-', '')
  return `${compact.slice(0, 5)}-${compact.slice(5)}`
}

export default function CheckinRegistrationsPage() {
  const [eventId, setEventId] = useState('')
  const [event, setEvent] = useState<BackendEventProduct | null>(null)
  const [items, setItems] = useState<BackendEventRegistration[]>([])
  const [status, setStatus] = useState<'all' | BackendEventRegistration['status']>('all')
  const [keyword, setKeyword] = useState('')
  const [passportNo, setPassportNo] = useState('')
  const [passportAdding, setPassportAdding] = useState(false)

  async function loadRegistrations(nextStatus = status, currentEventId = eventId) {
    const token = ensureStaffLoggedIn('/pages/checkin/events/index')
    if (!token) {
      return
    }
    if (!currentEventId) return
    try {
      const result = await backend.staffCheckinRegistrations(token, {
        kind: 'event',
        productId: currentEventId,
        status: nextStatus === 'all' ? '' : nextStatus,
        keyword,
        pageSize: '1000',
      })
      const nextItems = result.items as BackendEventRegistration[]
      setItems(nextItems)
      setEvent(nextItems[0]?.event || event)
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '名单加载失败', icon: 'none' })
    }
  }

  async function scanCheckin() {
    const token = ensureStaffLoggedIn('/pages/checkin/events/index')
    if (!token || !eventId) return
    try {
      const scan = await Taro.scanCode({ onlyFromCamera: false })
      const result = await backend.staffCheckinScanUnified(token, {
        kind: 'event',
        productId: eventId,
        checkinCode: scan.result,
        source: 'miniapp_scan'
      })
      await loadRegistrations(status, eventId)
      Taro.showToast({ title: result.alreadyCheckedIn ? '已核销过' : '核销成功', icon: 'success' })
      Taro.navigateTo({ url: `/pages/checkin/detail/index?id=${encodeURIComponent(result.registration.id)}&eventId=${encodeURIComponent(eventId)}` })
    } catch (error) {
      Taro.showToast({ title: checkinErrorMessage(error), icon: 'none' })
    }
  }

  async function addByPassport(nextPassportNo = passportNo) {
    const token = ensureStaffLoggedIn('/pages/checkin/events/index')
    if (!token || !eventId || passportAdding) return
    const normalized = extractPassportNo(nextPassportNo)
    if (!normalized) {
      Taro.showToast({ title: '请输入或扫描通行证号', icon: 'none' })
      return
    }
    setPassportAdding(true)
    try {
      const result = await backend.staffCheckinPassportRegistration(token, {
        kind: 'event',
        productId: eventId,
        passportNo: normalized,
        note: '小程序核销端通行证补录',
        checkIn: true,
        source: 'miniapp_passport'
      })
      await loadRegistrations(status, eventId)
      setPassportNo('')
      Taro.showToast({ title: result.alreadyRegistered ? '已在名单并核销' : '补录并核销成功', icon: 'success' })
      Taro.navigateTo({ url: `/pages/checkin/detail/index?id=${encodeURIComponent(result.registration.id)}&eventId=${encodeURIComponent(eventId)}` })
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '通行证补录失败', icon: 'none' })
    } finally {
      setPassportAdding(false)
    }
  }

  async function scanPassport() {
    const token = ensureStaffLoggedIn('/pages/checkin/events/index')
    if (!token || !eventId) return
    try {
      const scan = await Taro.scanCode({ onlyFromCamera: false })
      const normalized = extractPassportNo(scan.result)
      setPassportNo(normalized || scan.result)
      await addByPassport(scan.result)
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '扫码失败', icon: 'none' })
    }
  }

  useLoad((query) => {
    const nextEventId = String(query.eventId || '')
    setEventId(nextEventId)
    void loadRegistrations('all', nextEventId)
  })

  useDidShow(() => {
    if (eventId) void loadRegistrations(status, eventId)
  })

  const counts = useMemo(() => ({
    total: items.length,
    checked: items.filter((item) => item.status === 'checked_in').length,
  }), [items])
  const visibleItems = useMemo(() => {
    const search = keyword.trim()
    if (!search) return items
    return items.filter((item) => `${item.userName || ''}${item.userPhone || ''}${item.userOrganization || ''}${item.registrationNo || ''}${item.orderNo || ''}${item.checkinCode || ''}`.includes(search))
  }, [items, keyword])

  return (
    <Page title={event?.title || '报名名单'} subtle={`${counts.checked}/${counts.total} 已核销`}>
      <View className="checkin-action-grid">
        <Button className="checkin-scan-btn" onClick={scanCheckin}>扫核销码</Button>
        <Button className="checkin-passport-btn" loading={passportAdding} onClick={scanPassport}>扫通行证补录</Button>
      </View>
      <View className="checkin-passport-row">
        <Input
          className="checkin-passport-input"
          value={passportNo}
          placeholder="输入通行证号，如 KQHVP-58209"
          onInput={(event) => setPassportNo(String(event.detail.value || '').toUpperCase())}
        />
        <Button className="checkin-passport-add" loading={passportAdding} onClick={() => void addByPassport()}>
          加入并核销
        </Button>
      </View>

      <Input
        className="checkin-search"
        value={keyword}
        placeholder="搜索姓名、手机号、单位、报名号、订单号、核销码"
        onInput={(event) => setKeyword(String(event.detail.value || ''))}
      />

      <View className="checkin-filter">
        {[
          ['all', '全部'],
          ['registered', '未核销'],
          ['pending_payment', '待支付'],
          ['waitlisted', '候补'],
          ['checked_in', '已核销'],
          ['cancelled', '已取消'],
        ].map(([value, label]) => (
          <View
            key={value}
            className={status === value ? 'checkin-filter-chip active' : 'checkin-filter-chip'}
            onClick={() => {
              const next = value as typeof status
              setStatus(next)
              void loadRegistrations(next, eventId)
            }}
          >
            {label}
          </View>
        ))}
      </View>

      <View className="checkin-list">
        {visibleItems.map((item) => (
          <View key={item.id} className="checkin-person" onClick={() => Taro.navigateTo({ url: `/pages/checkin/detail/index?id=${encodeURIComponent(item.id)}&eventId=${encodeURIComponent(eventId)}` })}>
            <View className="checkin-person-main">
              <Text className="checkin-person-name">{item.userName || '未填写姓名'}</Text>
              <Text className="checkin-person-meta">{item.userPhone || '-'} · {memberLabel(item.membershipLevel)}</Text>
            </View>
              <Text className={item.status === 'checked_in' ? 'checkin-status done' : item.status === 'registered' ? 'checkin-status' : 'checkin-status muted'}>{statusLabel(item.status)}</Text>
          </View>
        ))}
        {!visibleItems.length && <View className="checkin-empty">暂无匹配报名人</View>}
      </View>
    </Page>
  )
}
