'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { useParams } from 'next/navigation'
import { ChevronRight, PlayCircle } from 'lucide-react'
import { useApp } from '@/components/providers/AppProvider'
import { CheckinQrCode } from '@/components/shared/CheckinQrCode'
import { backend, type BackendCourseProduct, type BackendCourseRegistration } from '@/lib/backend'

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

function formatCourseTime(value?: string | null) {
  if (!value) return '随时学习'
  const date = new Date(value)
  return `${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

export default function AccountCourseContentPage() {
  const params = useParams<{ id: string }>()
  const { user, token } = useApp()
  const [activeChapter, setActiveChapter] = useState(0)
  const [course, setCourse] = useState<BackendCourseProduct | null>(null)
  const [registration, setRegistration] = useState<BackendCourseRegistration | null>(null)
  const [loaded, setLoaded] = useState(false)
  const purchased = Boolean(registration)

  useEffect(() => {
    if (!user) return
    setLoaded(false)
    void (async () => {
      let currentRegistration: BackendCourseRegistration | null = null
      let courseKey = params.id
      if (token) {
        try {
          currentRegistration = await backend.accountCourseRegistration(token, params.id)
          courseKey = currentRegistration.productId || currentRegistration.course?.id || params.id
        } catch {
          const registrationResult = await backend.accountCourseRegistrations(token)
          currentRegistration = registrationResult.items.find((item) => item.productId === params.id || item.course?.id === params.id || item.course?.slug === params.id) || null
          courseKey = currentRegistration?.productId || currentRegistration?.course?.id || params.id
        }
      }
      const courseItem = currentRegistration?.course || await backend.courseProduct(courseKey)
      return { courseItem, currentRegistration }
    })()
      .then(({ courseItem, currentRegistration }) => {
        setCourse(courseItem)
        setRegistration(currentRegistration)
      })
      .catch(() => {
        setCourse(null)
        setRegistration(null)
      })
      .finally(() => setLoaded(true))
  }, [params.id, token, user])

  if (!user) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center">
          <h1 className="text-2xl font-extrabold text-ink">尚未登录</h1>
          <Link href="/login?redirect=%2Faccount" className="mt-7 inline-flex rounded-[4px] bg-brand px-6 py-3 text-sm font-extrabold text-white">去登录</Link>
        </div>
      </section>
    )
  }

  if (!loaded) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] border border-line bg-white p-10 text-center">
          <h1 className="text-2xl font-extrabold text-ink">课程加载中</h1>
        </div>
      </section>
    )
  }

  if (!course || !purchased) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center">
          <h1 className="text-2xl font-extrabold text-ink">暂无课程权益</h1>
          <p className="mt-3 text-sm text-muted">加入课程后，可在这里查看课程内容和学习资料。</p>
          <Link href="/courses" className="mt-7 inline-flex rounded-[4px] bg-brand px-6 py-3 text-sm font-extrabold text-white">浏览课程</Link>
        </div>
      </section>
    )
  }

  const chapterCount = Math.min(course.lessonCount || 6, 6)
  const coverStyle = course.coverUrl
    ? { backgroundImage: `url(${course.coverUrl})` }
    : { backgroundImage: 'linear-gradient(135deg,#eef3f8,#dbe6f2)' }
  const isRecordedCourse = course.courseFormat === '线上课程'
  const isLiveCourse = course.courseFormat === '直播课'
  const lessonModules = course.lessonModules?.length ? course.lessonModules : []
  const moduleTitles = lessonModules.length ? lessonModules.map((item) => item.title) : (course.modules || [])
  const activeModule = lessonModules[activeChapter]
  const activeTitle = moduleTitles[activeChapter] || chapterTitle(activeChapter)
  const isOfflineCourse = course.courseFormat === '线下培训'

  return (
    <section className="bg-bg py-8">
      <div className="mx-auto max-w-[1180px] px-6">
        <nav className="mb-6 flex flex-wrap items-center gap-2 text-sm text-muted">
          <Link href="/account/membership" className="hover:text-brand">我的</Link>
          <ChevronRight className="h-4 w-4 text-soft" />
          <Link href="/account/courses" className="hover:text-brand">我的课程</Link>
          <ChevronRight className="h-4 w-4 text-soft" />
          <span className="font-bold text-ink">{course.title}</span>
        </nav>

        <div className="mx-auto max-w-[900px]">
          <main className="overflow-hidden rounded-[4px] border border-line bg-white shadow-[0_12px_34px_rgba(15,23,42,0.04)]">
            {isRecordedCourse ? (
              <div className="bg-ink p-6 text-white">
                {activeModule?.videoUrl ? (
                  <video key={activeModule.videoUrl} controls className="aspect-video w-full bg-black">
                    <source src={activeModule.videoUrl} />
                  </video>
                ) : (
                  <div className="grid min-h-[340px] place-items-center border border-white/10 bg-white/[0.04] text-center">
                    <div>
                      <PlayCircle className="mx-auto h-14 w-14 text-white/75" strokeWidth={1.5} />
                      <div className="mt-5 text-xl font-extrabold">第 {activeChapter + 1} 课：{activeTitle}</div>
                      <p className="mt-3 max-w-[520px] text-sm leading-7 text-white/60">当前模块暂未上传视频，点击下方目录可切换其他模块。</p>
                    </div>
                  </div>
                )}
              </div>
            ) : isLiveCourse ? (
              <div className="grid aspect-[16/7] place-items-center bg-cover bg-center text-white" style={course.coverUrl ? { backgroundImage: `linear-gradient(180deg,rgba(15,23,42,0.2),rgba(15,23,42,0.64)),url(${course.coverUrl})` } : coverStyle}>
                <div className="text-center">
                  <div className="text-2xl font-extrabold">{course.courseStatus === 'completed' ? '直播已结束' : course.courseStatus === 'ongoing' ? '直播进行中' : '直播未开始'}</div>
                  {course.courseStatus === 'ongoing' && course.liveUrl ? <a href={course.liveUrl} className="mt-5 inline-flex rounded-[4px] bg-white px-5 py-2.5 text-sm font-extrabold text-ink">进入直播</a> : null}
                  {!course.coverUrl && <div className="mt-4 text-sm font-bold text-muted">暂无课程封面</div>}
                </div>
              </div>
            ) : (
              <div className="grid aspect-[16/7] place-items-center bg-cover bg-center" style={coverStyle}>
                {!course.coverUrl && <div className="text-sm font-extrabold text-muted">暂无课程封面</div>}
              </div>
            )}

            <div className="p-7 text-center">
              <h1 className="text-3xl font-extrabold text-ink">{course.title}</h1>
              <p className="mx-auto mt-3 max-w-[720px] text-sm leading-7 text-muted">{course.summary}</p>

              <div className="mt-6 grid gap-4 border-y border-line py-5 text-sm md:grid-cols-3">
                <div>
                  <div className="text-xs font-bold text-muted">课程</div>
                  <div className="mt-1 font-extrabold text-ink">{course.instructor}</div>
                </div>
                <div>
                  <div className="text-xs font-bold text-muted">课时</div>
                  <div className="mt-1 font-extrabold text-ink">{course.lessonCount} 课时</div>
                </div>
                <div>
                  <div className="text-xs font-bold text-muted">时间/地点</div>
                  <div className="mt-1 font-extrabold text-ink">{course.startsAt ? `${formatCourseTime(course.startsAt)} · ${course.location || course.courseFormat}` : `随时学习 · ${course.courseFormat || '线上课程'}`}</div>
                </div>
              </div>

              {isOfflineCourse && registration && (
                <div className="mx-auto mt-7 grid max-w-[720px] gap-5 rounded-[4px] border border-line bg-bg/50 p-5 text-left md:grid-cols-[1fr_auto] md:items-center">
                  <div>
                    <div className="text-sm font-extrabold text-brand">线下报名凭证</div>
                    <div className="mt-3 grid gap-3 text-sm sm:grid-cols-2">
                      <div>
                        <div className="text-xs font-bold text-muted">核销码</div>
                        <div className="mt-1 text-lg font-extrabold text-ink">{registration.checkinCode}</div>
                      </div>
                      <div>
                        <div className="text-xs font-bold text-muted">核销状态</div>
                        <div className="mt-1 text-lg font-extrabold text-ink">{registration.status === 'checked_in' ? '已核销' : '待核销'}</div>
                      </div>
                    </div>
                    <p className="mt-3 text-xs font-bold leading-6 text-muted">到场后向工作人员出示二维码完成签到核销。已下架课程不影响已购买用户查看报名凭证。</p>
                  </div>
                  <CheckinQrCode value={registration.checkinCode} className="h-40 w-40" />
                </div>
              )}

              <div className="mx-auto mt-7 max-w-[720px] text-left">
                <h2 className="text-xl font-extrabold text-ink">课程目录</h2>
                <div className="mt-4 divide-y divide-line border-y border-line">
                  {Array.from({ length: chapterCount }).map((_, index) => (
                    <button
                      key={index}
                      type="button"
                      onClick={() => setActiveChapter(index)}
                      className={`flex w-full items-center justify-between gap-5 px-2 py-4 text-left transition ${
                        activeChapter === index ? 'bg-brand-light/55 text-brand' : 'hover:bg-bg'
                      }`}
                    >
                      <div className="flex items-center gap-3">
                        <span className="w-7 text-sm font-extrabold text-brand">{String(index + 1).padStart(2, '0')}</span>
                        <div className="text-sm font-extrabold text-ink">{moduleTitles[index] || chapterTitle(index)}</div>
                      </div>
                      <span className="text-xs font-bold text-muted">{isRecordedCourse ? '切换视频' : '查看'}</span>
                    </button>
	                  ))}
	                </div>
	                {activeModule?.materialUrl && (
	                  <a href={activeModule.materialUrl} target="_blank" rel="noreferrer" className="mt-4 inline-flex h-10 items-center rounded-[4px] border border-line px-4 text-sm font-extrabold text-muted hover:border-brand hover:text-brand">
	                    下载本节资料
	                  </a>
	                )}
	              </div>
            </div>
          </main>
        </div>
      </div>
    </section>
  )
}
