import { ScrollView, Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import { backend, type BackendCourseProduct, type BackendCourseRegistration, type BackendEventRegistration } from '@/api/backend'
import { EmptyState, Page, ProductImage, StatusSide } from '@/components/ui'
import { ensureLoggedIn, getToken } from '@/stores/storage'

type ActivityFilter = 'all' | 'course' | 'event' | 'active' | 'done'
type ActivityEntry = {
  id: string
  type: 'course' | 'event'
  title: string
  meta: string
  status: string
  cover: string
  url: string
  sortTime: number
  active: boolean
  done: boolean
  orange?: boolean
}

function formatCourseTime(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 registrationLabel(item?: BackendCourseRegistration) {
  if (!item) return ''
  if (item.status === 'pending_payment') return '待支付'
  if (item.status === 'waitlisted') return '候补中'
  if (item.status === 'checked_in') return '已核销'
  if (item.status === 'cancel_requested') return '取消处理中'
  if (item.status === 'cancelled') return '已取消'
  if (item.status === 'no_show') return '未到场'
  if (item.status === 'refunded') return '已关闭'
  return item.course?.courseFormat === '线下培训' ? '待核销' : '已开通'
}

function courseMeta(course: BackendCourseProduct, registration?: BackendCourseRegistration) {
  const status = registration ? registrationLabel(registration) : course.courseStatus === 'completed' ? '已结束' : '已购买'
  const place = course.courseFormat === '线下培训' ? course.location || '地点待定' : course.courseFormat === '直播课' ? '直播课程' : '线上学习'
  return `${course.courseFormat || '课程'} · ${formatCourseTime(course.startsAt)} · ${place} · ${status}`
}

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 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 eventDone(item: BackendEventRegistration) {
  if (['checked_in', 'cancel_requested', 'cancelled', 'no_show', 'refunded'].includes(item.status)) return true
  const end = item.event?.endsAt || item.event?.startsAt
  return Boolean(end && new Date(end).getTime() < Date.now())
}

export default function CoursesPage() {
  const [courses, setCourses] = useState<BackendCourseProduct[]>([])
  const [registrations, setRegistrations] = useState<BackendCourseRegistration[]>([])
  const [events, setEvents] = useState<BackendEventRegistration[]>([])
  const [courseIds, setCourseIds] = useState<string[]>([])
  const [filter, setFilter] = useState<ActivityFilter>('all')
  const [loading, setLoading] = useState(false)

  async function loadCourses() {
    const user = ensureLoggedIn('/pages/account/courses/index')
    const token = getToken()
    if (!user || !token) return
    setLoading(true)
    try {
      const [catalogResult, orderResult, registrationResult, eventResult] = await Promise.all([
        backend.courseCatalog(),
        backend.accountOrders(token),
        backend.accountCourseRegistrations(token),
        backend.accountEventRegistrations(token),
      ])
      const orderCourseIds = orderResult.items.flatMap((order) => order.items)
        .filter((item) => item.productType === 'course')
        .map((item) => item.productId)
      const registrationCourseIds = registrationResult.items.map((item) => item.productId)
      setCourses(catalogResult.items)
      setRegistrations(registrationResult.items)
      setEvents(eventResult.items)
      setCourseIds(Array.from(new Set([...orderCourseIds, ...registrationCourseIds])))
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '课程加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

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

  const courseEntries: ActivityEntry[] = []
  courseIds.forEach((id) => {
    const course = courses.find((item) => item.id === id || item.slug === id) || registrations.find((item) => item.productId === id)?.course
    if (!course) return
    const registration = registrations.find((item) => item.productId === course.id)
    const status = registration ? registrationLabel(registration) : course.courseStatus === 'completed' ? '已结束' : '权益'
    const done = status === '已核销' || status === '已关闭' || course.courseStatus === 'completed'
    courseEntries.push({
      id: `course-${registration?.id || course.id}`,
      type: 'course',
      title: course.title,
      meta: courseMeta(course, registration),
      status,
      cover: course.coverUrl || 'course',
      url: `/pages/account/courses/detail/index?id=${encodeURIComponent(registration?.id || course.id)}`,
      sortTime: new Date(course.startsAt || registration?.createdAt || 0).getTime() || 0,
      active: !done,
      done,
      orange: registration?.status === 'pending_payment' || registration?.status === 'waitlisted'
    })
  })

  const eventEntries: ActivityEntry[] = events.map((item) => {
    const done = eventDone(item)
    const status = eventStatusLabel(item.status)
    return {
      id: `event-${item.id}`,
      type: 'event',
      title: item.event?.title || '活动',
      meta: `活动 · ${eventTime(item.event?.startsAt)} · ${item.event?.isOnline ? '线上活动' : item.event?.location || '地点待定'} · ${status}`,
      status,
      cover: item.event?.coverUrl || 'event',
      url: `/pages/account/events/detail/index?id=${encodeURIComponent(item.id)}`,
      sortTime: new Date(item.event?.startsAt || item.createdAt || 0).getTime() || 0,
      active: !done,
      done,
      orange: item.status === 'pending_payment' || item.status === 'waitlisted'
    }
  })

  const entries = [...courseEntries, ...eventEntries]
    .sort((a, b) => {
      if (a.done !== b.done) return a.done ? 1 : -1
      return (a.sortTime || 0) - (b.sortTime || 0)
    })
  const filterOptions: Array<{ key: ActivityFilter; label: string; count: number }> = [
    { key: 'all', label: '全部', count: entries.length },
    { key: 'course', label: '课程', count: courseEntries.length },
    { key: 'event', label: '活动', count: eventEntries.length },
    { key: 'active', label: '待参加', count: entries.filter((item) => item.active).length },
    { key: 'done', label: '已完成', count: entries.filter((item) => item.done).length },
  ]
  const visibleEntries = entries.filter((item) => {
    if (filter === 'course') return item.type === 'course'
    if (filter === 'event') return item.type === 'event'
    if (filter === 'active') return item.active
    if (filter === 'done') return item.done
    return true
  })
  const activeFilterLabel = filterOptions.find((item) => item.key === filter)?.label || '课程活动'

  return (
    <Page title="课程活动" subtle={loading ? '正在同步课程与活动记录' : `当前 ${entries.length} 项课程活动`}>
      <ScrollView scrollX className="category-scroll activity-filter-scroll" enhanced showScrollbar={false}>
        {filterOptions.map((item) => (
          <Text key={item.key} className={item.key === filter ? 'category-chip active' : 'category-chip'} onClick={() => setFilter(item.key)}>
            {item.label} {item.count}
          </Text>
        ))}
      </ScrollView>

      {!entries.length && !loading ? (
        <EmptyState title="暂无课程活动" text="加入课程或报名活动后，学习入口、线下安排和核销状态都会在这里显示。" />
      ) : !visibleEntries.length && !loading ? (
        <EmptyState title={`暂无${activeFilterLabel}`} text="切换上方筛选胶囊查看其他课程或活动。" />
      ) : (
        <View className="service-list">
          {visibleEntries.map((item) => (
            <View key={item.id} className="service-row" onClick={() => Taro.navigateTo({ url: item.url })}>
              <ProductImage className="service-thumb" src={item.cover} />
              <View style={{ flex: 1 }}>
                <Text className="row-title">{item.title}</Text>
                <Text className="row-sub">{item.meta}</Text>
              </View>
              <StatusSide value={item.status} orange={item.orange} />
            </View>
          ))}
        </View>
      )}
    </Page>
  )
}
