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

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

export default function CheckinCoursesPage() {
  const [items, setItems] = useState<BackendCheckinProject[]>([])
  const [loading, setLoading] = useState(false)

  async function loadCourses() {
    const token = ensureStaffLoggedIn('/pages/checkin/events/index')
    if (!token) {
      return
    }
    setLoading(true)
    try {
      const result = await backend.staffCheckinProjects(token, { kind: 'course', range: 'all' })
      setItems(result.items)
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '课程加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  useDidShow(() => {
    void loadCourses()
  })

  return (
    <Page title="选择课程" subtle={loading ? '正在同步报名名单' : `当前 ${items.length} 个线下课程`}>
      <View className="checkin-list">
        {items.map((item) => (
          <View key={item.id} className="checkin-event" onClick={() => Taro.navigateTo({ url: `/pages/checkin/course-registrations/index?courseId=${encodeURIComponent(item.id)}` })}>
            <View className="checkin-event-main">
              <Text className="checkin-event-title">{item.title}</Text>
              <Text className="checkin-event-meta">{formatTime(item.startsAt)} · {item.location || '未设地点'}</Text>
            </View>
            <View className="checkin-count">
              <Text className="checkin-count-main">{item.registeredCount}</Text>
              <Text className="checkin-count-sub">{item.capacity ? `/${item.capacity}` : '报名'}</Text>
            </View>
          </View>
        ))}
        {!items.length && !loading && <View className="checkin-empty">暂无可核销线下课程</View>}
      </View>
    </Page>
  )
}
