import { Text, Video, View } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useMemo, useState } from 'react'
import { backend, type BackendCourseProduct, type BackendCourseRegistration } from '@/api/backend'
import { EmptyState, MetaRow, Page, ProductImage } from '@/components/ui'
import { ensureLoggedIn, getToken } from '@/stores/storage'
import { createQrMatrix } from '@/utils/qr-code'

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

function registrationLabel(item?: BackendCourseRegistration | null) {
  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 liveState(course: BackendCourseProduct) {
  const start = course.startsAt ? new Date(course.startsAt) : null
  const now = new Date()
  if (course.courseStatus === 'completed') return 'ended'
  if (course.courseStatus === 'ongoing') return 'live'
  if (start && now >= start && course.liveUrl) return 'live'
  if (start && now >= start) return 'ended'
  return 'upcoming'
}

function liveStateLabel(state: string) {
  if (state === 'live') return '直播进行中'
  if (state === 'ended') return '直播已结束'
  return '直播未开始'
}

function chapterTitle(index: number) {
  const titles = ['课程导入与背景认知', '核心框架和方法拆解', '典型案例讲解', '工具模板与实操清单', '项目推进和风险控制', '复盘答疑与后续行动']
  return titles[index] || `课程章节 ${index + 1}`
}

function CheckinQr({ value }: { value: string }) {
  const matrix = useMemo(() => createQrMatrix(value || 'NO-CHECKIN'), [value])
  const cellSize = `${100 / matrix.length}%`
  return (
    <View className="checkin-qr-grid">
      {matrix.flatMap((row, y) => row.map((dark, x) => (
        <View key={`${x}-${y}`} className={dark ? 'checkin-qr-cell dark' : 'checkin-qr-cell'} style={{ width: cellSize, height: cellSize }} />
      )))}
    </View>
  )
}

export default function CourseDetailPage() {
  const [course, setCourse] = useState<BackendCourseProduct | null>(null)
  const [registration, setRegistration] = useState<BackendCourseRegistration | null>(null)
  const [activeModule, setActiveModule] = useState(0)

  async function loadCourse(id: string) {
    const user = ensureLoggedIn(`/pages/account/courses/detail/index?id=${encodeURIComponent(id)}`)
    const token = getToken()
    if (!user || !token || !id) return
    try {
      let currentRegistration: BackendCourseRegistration | null = null
      let courseKey = id
      try {
        currentRegistration = await backend.accountCourseRegistration(token, id)
        courseKey = currentRegistration.productId || currentRegistration.course?.id || id
      } catch {
        const registrationResult = await backend.accountCourseRegistrations(token)
        currentRegistration = registrationResult.items.find((item) => item.productId === id || item.course?.id === id || item.course?.slug === id) || null
        courseKey = currentRegistration?.productId || currentRegistration?.course?.id || id
      }
      const courseResult = currentRegistration?.course || await backend.courseProduct(courseKey)
      setCourse(courseResult)
      setRegistration(currentRegistration)
      setActiveModule(0)
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '课程加载失败', icon: 'none' })
    }
  }

  useLoad((query) => {
    void loadCourse(String(query.id || ''))
  })

  function copyLink(value: string, message: string) {
    void Taro.setClipboardData({ data: value })
    Taro.showToast({ title: message, icon: 'none' })
  }

  if (!course) return <Page title="课程加载中" subtle="正在同步课程信息" />

  const isRecordedCourse = course.courseFormat === '线上课程'
  const isLiveCourse = course.courseFormat === '直播课'
  const isOfflineCourse = course.courseFormat === '线下培训'
  const modules = course.lessonModules?.length ? course.lessonModules : (course.modules || []).map((title, index) => ({
    id: String(index),
    title,
    description: '',
    videoUrl: '',
    materialUrl: '',
    durationMinutes: 0,
    sortOrder: index + 1,
    status: 'published',
  }))
  const displayModules = modules.length ? modules : Array.from({ length: Math.min(course.lessonCount || 3, 6) }, (_, index) => ({
    id: String(index),
    title: chapterTitle(index),
    description: '',
    videoUrl: '',
    materialUrl: '',
    durationMinutes: 0,
    sortOrder: index + 1,
    status: 'published',
  }))
  const active = displayModules[Math.min(activeModule, displayModules.length - 1)]
  const currentLiveState = liveState(course)
  const canShowQr = isOfflineCourse && registration?.status === 'registered' && Boolean(registration.checkinCode)

  return (
    <Page title={course.title} subtle={`${course.courseFormat || '课程'} · ${course.instructor || '研究院讲师'}`}>
      <View className="course-detail-shell">
        {isRecordedCourse ? (
          <View className="course-player">
            {active?.videoUrl ? (
              <Video key={active.videoUrl} className="course-video" src={active.videoUrl} controls />
            ) : (
              <View className="course-media-empty">
                <Text className="course-media-title">第 {activeModule + 1} 课：{active?.title || '课程视频'}</Text>
                <Text className="course-media-text">当前模块暂未上传视频，可先查看目录和资料。</Text>
              </View>
            )}
          </View>
        ) : (
          <ProductImage className="course-detail-cover" src={course.coverUrl || 'course'} label={isLiveCourse ? '直播课程' : isOfflineCourse ? '线下培训' : '课程'} />
        )}

        <View className="course-detail-main">
          <Text className="course-detail-title">{isRecordedCourse ? active?.title || course.title : course.title}</Text>
          <Text className="course-detail-summary">{active?.description || course.summary}</Text>

          <View className="course-facts">
            <MetaRow label="课程形式" value={course.courseFormat || '-'} />
            <MetaRow label="课时" value={`${course.lessonCount || displayModules.length || 0} 课时`} />
            <MetaRow label="时间" value={formatCourseTime(course.startsAt)} />
            <MetaRow label="地点" value={isOfflineCourse ? course.location || '-' : '线上'} />
          </View>

          {isLiveCourse && (
            <View className="course-live-box">
              <Text className={`course-live-state ${currentLiveState}`}>{liveStateLabel(currentLiveState)}</Text>
              <Text className="course-live-note">
                {currentLiveState === 'upcoming' ? '直播开始前请留意平台通知。' : currentLiveState === 'live' ? '复制直播入口后在微信或浏览器打开。' : '直播结束后，可查看回放或课程资料。'}
              </Text>
              {currentLiveState === 'live' && course.liveUrl && (
                <View className="primary-btn course-inline-btn" onClick={() => copyLink(course.liveUrl || '', '直播链接已复制')}>复制直播入口</View>
              )}
              {currentLiveState === 'ended' && course.replayUrl && (
                <View className="ghost-btn course-inline-btn" onClick={() => copyLink(course.replayUrl || '', '回放链接已复制')}>复制回放链接</View>
              )}
            </View>
          )}

          {isOfflineCourse && (
            <View className="checkin-pass-card">
              <View className="checkin-pass-copy">
                <Text className="checkin-pass-label">线下报名凭证</Text>
                <Text className="checkin-pass-title">{registrationLabel(registration)}</Text>
                <Text className="checkin-pass-text">
                  {canShowQr ? '到场后向工作人员出示二维码完成签到核销。' : registration?.status === 'pending_payment' ? '完成支付后会生成有效核销凭证。' : '当前状态不需要出示核销二维码。'}
                </Text>
                <MetaRow label="核销码" value={registration?.checkinCode || '-'} />
                <MetaRow label="核销时间" value={formatFullTime(registration?.checkedInAt)} />
              </View>
              <View className="checkin-pass-qr">
                {canShowQr ? <CheckinQr value={registration?.checkinCode || ''} /> : <Text className="checkin-pass-state">{registrationLabel(registration)}</Text>}
              </View>
            </View>
          )}

          <View className="course-module-list">
            <Text className="course-module-head">课程目录</Text>
            {displayModules.map((item, index) => (
              <View
                key={item.id || index}
                className={index === activeModule ? 'course-module active' : 'course-module'}
                onClick={() => setActiveModule(index)}
              >
                <Text className="course-module-index">{String(index + 1).padStart(2, '0')}</Text>
                <View className="course-module-copy">
                  <Text className="course-module-title">{item.title || chapterTitle(index)}</Text>
                  <Text className="course-module-sub">{item.durationMinutes ? `${item.durationMinutes} 分钟` : isRecordedCourse ? '切换学习' : '查看安排'}</Text>
                </View>
              </View>
            ))}
          </View>

          {active?.materialUrl && (
            <View className="ghost-btn course-inline-btn" onClick={() => copyLink(active.materialUrl, '资料链接已复制')}>复制本节资料链接</View>
          )}

          {course.accessNote && <Text className="course-access-note">{course.accessNote}</Text>}
        </View>
      </View>
      {!registration && <EmptyState compact title="暂无报名记录" text="如果刚完成支付，请稍后返回刷新课程权益。" />}
    </Page>
  )
}
