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

type WorkbenchTab = 'event' | 'course'

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 CheckinWorkbenchPage() {
  const [tab, setTab] = useState<WorkbenchTab>('event')
  const [items, setItems] = useState<BackendCheckinProject[]>([])
  const [loading, setLoading] = useState(false)

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

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

  const stats = useMemo(() => items.reduce((acc, item) => {
    const startsAt = item.startsAt ? new Date(item.startsAt) : null
    const now = new Date()
    const today = startsAt && startsAt.getFullYear() === now.getFullYear() && startsAt.getMonth() === now.getMonth() && startsAt.getDate() === now.getDate()
    return {
      todayProjects: acc.todayProjects + (today ? 1 : 0),
      pending: acc.pending + Number(item.pendingCount ?? Math.max(Number(item.registeredCount || 0) - Number(item.checkedInCount || 0), 0)),
      checked: acc.checked + Number(item.checkedInCount || 0),
    }
  }, { todayProjects: 0, pending: 0, checked: 0 }), [items])

  const currentItems = items.filter((item) => item.kind === tab)
  const eventCount = items.filter((item) => item.kind === 'event').length
  const courseCount = items.filter((item) => item.kind === 'course').length

  return (
    <Page title="核销工作台" subtle={loading ? '正在同步报名名单' : '活动与线下课程'}>
      <View className="checkin-dashboard">
        <View className="checkin-stat">
          <Text className="checkin-stat-value">{stats.todayProjects}</Text>
          <Text className="checkin-stat-label">今日项目</Text>
        </View>
        <View className="checkin-stat">
          <Text className="checkin-stat-value">{stats.pending}</Text>
          <Text className="checkin-stat-label">未核销</Text>
        </View>
        <View className="checkin-stat">
          <Text className="checkin-stat-value">{stats.checked}</Text>
          <Text className="checkin-stat-label">已核销</Text>
        </View>
      </View>

      <View className="checkin-tabs">
        {[
          ['event', `活动 ${eventCount}`],
          ['course', `线下课程 ${courseCount}`],
        ].map(([value, label]) => (
          <View key={value} className={tab === value ? 'checkin-tab active' : 'checkin-tab'} onClick={() => setTab(value as WorkbenchTab)}>
            {label}
          </View>
        ))}
      </View>

      <View className="checkin-list">
        {currentItems.map((item) => (
          <View
            key={`${item.kind}-${item.productId}`}
            className="checkin-event"
            onClick={() => Taro.navigateTo({
              url: item.kind === 'event'
                ? `/pages/checkin/registrations/index?eventId=${encodeURIComponent(item.productId)}`
                : `/pages/checkin/course-registrations/index?courseId=${encodeURIComponent(item.productId)}`,
            })}
          >
            <View className="checkin-event-main">
              <Text className="checkin-event-title">{item.title}</Text>
              <Text className="checkin-event-meta">{formatTime(item.startsAt)} · {item.location || '未设地点'}</Text>
              <Text className="checkin-event-meta">已核销 {item.checkedInCount || 0} / 报名 {item.registeredCount || 0}{item.capacity ? ` · 名额 ${item.capacity}` : ''}</Text>
            </View>
            <View className="checkin-count">
              <Text className="checkin-count-main">{item.pendingCount ?? Math.max(Number(item.registeredCount || 0) - Number(item.checkedInCount || 0), 0)}</Text>
              <Text className="checkin-count-sub">待核销</Text>
            </View>
          </View>
        ))}
        {!currentItems.length && !loading && <View className="checkin-empty">{tab === 'event' ? '暂无可核销活动' : '暂无可核销线下课程'}</View>}
      </View>
    </Page>
  )
}
