import { notFound } from 'next/navigation'
import type { Metadata } from 'next'
import Link from 'next/link'
import { BookOpen, CalendarDays, ChevronRight, Clock3, ExternalLink, FileText, UserRound } from 'lucide-react'
import { AddToCartButton } from '@/components/commerce/AddToCartButton'
import { ImagePlaceholder } from '@/components/shared/ImagePlaceholder'
import { getCourseProduct, getCourseProducts } from '@/lib/server-products'
import type { Course } from '@/types'

export async function generateStaticParams() {
  const courses = await getCourseProducts()
  return courses.map((course) => ({ slug: course.slug }))
}

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params
  const course = await getCourseProduct(slug)
  return { title: course ? `${course.title} · 培训课程` : '培训课程' }
}

function accessForLevel(course: Course, level: 0 | 1 | 2) {
  if (level === 2) return course.seniorAccess || 'paid'
  if (level === 1) return course.juniorAccess || 'paid'
  return course.registeredAccess || 'paid'
}

function priceForLevel(course: Course, level: 0 | 1 | 2) {
  const amount = level === 2 ? course.seniorPriceAmount : level === 1 ? course.juniorPriceAmount : course.registeredPriceAmount
  return Math.round((amount ?? course.price * 100) / 100)
}

function lowestVisiblePrice(course: Course) {
  const prices = ([0, 1, 2] as const)
    .map((level) => accessForLevel(course, level) === 'closed' ? null : accessForLevel(course, level) === 'free' ? 0 : priceForLevel(course, level))
    .filter((value): value is number => value !== null)
  return prices.length ? Math.min(...prices) : 0
}

function offerText(course: Course) {
  const registered = accessForLevel(course, 0)
  const junior = accessForLevel(course, 1)
  const senior = accessForLevel(course, 2)
  const price = lowestVisiblePrice(course)
  const priceText = price === 0 ? '免费' : `¥${price}`
  if (registered === 'free' && junior === 'free' && senior === 'free') return { price: priceText, benefit: '全员免费' }
  if (registered === 'paid' && junior === 'free' && senior === 'free') return { price: priceText, benefit: '会员免费，注册用户付费' }
  if (registered === 'closed' && junior === 'free' && senior === 'free') return { price: priceText, benefit: '注册用户不开放，初级/高级会员免费' }
  if (registered === 'closed' && junior === 'paid' && senior === 'free') return { price: priceText, benefit: '注册用户不开放，初级会员收费，高级会员免费' }
  if (registered === 'closed' && junior === 'closed' && senior !== 'closed') return { price: priceText, benefit: senior === 'free' ? '注册用户和初级会员不开放，仅高级会员免费' : '注册用户和初级会员不开放，仅高级会员收费开放' }
  if (registered === 'paid' || junior === 'paid' || senior === 'paid') return { price: priceText, benefit: '按身份开放与定价' }
  return { price: priceText, benefit: '限指定身份开放' }
}

function formatStartDate(value: Date | null) {
  if (!value) return '随时学习'
  return `${value.getMonth() + 1}月${value.getDate()}日 ${String(value.getHours()).padStart(2, '0')}:00`
}

function liveState(course: Course) {
  const start = course.startsAt ? new Date(course.startsAt) : null
  const now = new Date()
  const status = String(course.status)
  if (status === 'completed') return 'ended'
  if (status === 'ongoing') return 'live'
  if (start && now >= start && status !== 'completed') return course.liveUrl ? 'live' : 'ended'
  return 'upcoming'
}

function getCourseDetailMeta(course: Course) {
  return {
    cover: course.coverLabel || `暂无课程封面：${course.title}`,
    audience: course.audience || '',
    outcomes: course.outcomes || [],
    modules: course.lessonModules?.length ? course.lessonModules.map((item) => item.title) : course.modules || [],
    accessNote: course.accessNote || '',
  }
}

function CourseUnavailablePage({ course }: { course: Course }) {
  return (
    <section className="border-b border-line bg-[#f7f9fc]">
      <div className="mx-auto max-w-[880px] px-6 py-16">
        <nav className="mb-8 flex flex-wrap items-center gap-2 text-sm text-muted">
          <Link href="/" className="hover:text-brand">首页</Link>
          <ChevronRight className="h-4 w-4 text-soft" />
          <Link href="/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="border border-line bg-white p-8 text-center shadow-[0_18px_44px_rgba(15,23,42,0.06)]">
          <div className="text-sm font-extrabold text-soft">COURSE UNAVAILABLE</div>
          <h1 className="mt-3 text-3xl font-extrabold text-ink">该课程已下架</h1>
          <p className="mx-auto mt-4 max-w-[560px] text-sm leading-7 text-muted">
            {course.title} 当前不再对外展示或购买。已经购买过的用户仍可在个人中心查看历史课程权益和学习记录。
          </p>
          <div className="mt-7 flex flex-wrap justify-center gap-3">
            <Link href="/account/courses" className="rounded-[4px] bg-brand px-5 py-2.5 text-sm font-extrabold text-white">查看我的课程</Link>
            <Link href="/courses" className="rounded-[4px] border border-line px-5 py-2.5 text-sm font-extrabold text-muted hover:border-brand hover:text-brand">返回课程目录</Link>
          </div>
        </div>
      </div>
    </section>
  )
}

export default async function CourseDetailPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const course = await getCourseProduct(slug)
  if (!course) notFound()
  if (course.productStatus !== 'published') return <CourseUnavailablePage course={course} />
  const startsAt = course.startsAt ? new Date(course.startsAt) : null
  const offer = offerText(course)
  const detailMeta = getCourseDetailMeta(course)
  const isOfflineCourse = course.courseFormat === '线下培训'
  const isLiveCourse = course.courseFormat === '直播课'
  const currentLiveState = isLiveCourse ? liveState(course) : null
  const isFull = isOfflineCourse && Boolean(course.capacity && (course.registeredCount || 0) >= course.capacity)

  return (
    <>
      <section className="border-b border-line bg-[#f7f9fc]">
        <div className="mx-auto max-w-[1280px] px-6 py-10">
          <nav className="mb-8 flex flex-wrap items-center gap-2 text-sm text-muted">
            <Link href="/" className="hover:text-brand">首页</Link>
            <ChevronRight className="h-4 w-4 text-soft" />
            <Link href="/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="grid gap-8 lg:grid-cols-[1fr_360px] lg:items-start">
            <main className="overflow-hidden rounded-[10px] border border-line bg-white shadow-[0_22px_58px_rgba(15,23,42,0.06)]">
              {course.coverUrl ? (
                <div className="relative h-[340px] border-b border-line bg-cover bg-center" style={{ backgroundImage: `url(${course.coverUrl})` }}>
                  {isLiveCourse && (
                    <div className="absolute inset-0 grid place-items-center bg-ink/35 text-center text-white">
                      <div>
                        <div className="text-2xl font-extrabold">{currentLiveState === 'live' ? '直播进行中' : currentLiveState === 'ended' ? '直播已结束' : '直播未开始'}</div>
                        {currentLiveState === 'live' && course.liveUrl && (
                          <a href={course.liveUrl} target="_blank" rel="noreferrer" className="mt-5 inline-flex items-center gap-2 rounded-[4px] bg-white px-5 py-2.5 text-sm font-extrabold text-ink">
                            进入直播 <ExternalLink className="h-4 w-4" />
                          </a>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              ) : (
                <ImagePlaceholder label={detailMeta.cover} className="h-[340px] border-0 border-b border-dashed border-[#9db6d3]" />
              )}

              <div className="p-8 md:p-10">
                <h1 className="text-[34px] font-extrabold leading-tight text-ink md:text-[48px]">{course.title}</h1>
                <p className="mt-5 max-w-[820px] text-base leading-8 text-text-body">{course.summary}</p>

                <div className="mt-8 grid gap-4 border-y border-line py-5 text-sm md:grid-cols-3">
                  <div className="flex gap-3">
                    <UserRound className="mt-0.5 h-4 w-4 text-brand" />
                    <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="flex gap-3">
                    <Clock3 className="mt-0.5 h-4 w-4 text-brand" />
                    <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="flex gap-3">
                    <CalendarDays className="mt-0.5 h-4 w-4 text-brand" />
                    <div>
                      <div className="text-xs font-bold text-muted">开课时间</div>
                      <div className="mt-1 font-extrabold text-ink">{formatStartDate(startsAt)}</div>
                    </div>
                  </div>
                </div>

                <section className="mt-10">
                  <h2 className="text-2xl font-extrabold text-ink">你将学到</h2>
                  {detailMeta.outcomes.length ? <div className="mt-5 grid gap-x-8 gap-y-4 md:grid-cols-2">
                    {detailMeta.outcomes.map((item, index) => (
                      <div key={item} className="flex gap-3 border-t border-line pt-4">
                        <span className="text-xs font-extrabold text-soft">0{index + 1}</span>
                        <span className="text-sm font-bold leading-7 text-text-body">{item}</span>
                      </div>
                    ))}
                  </div> : <div className="mt-5 border border-dashed border-line bg-bg px-4 py-5 text-sm font-bold text-muted">后台待补充学习成果</div>}
                </section>

                <section className="mt-12">
                  <h2 className="text-2xl font-extrabold text-ink">课程安排</h2>
                  {detailMeta.modules.length ? <div className="mt-5 divide-y divide-line border-y border-line">
                    {detailMeta.modules.map((item, index) => (
                      <div key={item} className="grid gap-4 py-5 md:grid-cols-[92px_1fr]">
                        <div className="text-sm font-extrabold text-brand">模块 {index + 1}</div>
                        <div className="font-extrabold text-ink">{item}</div>
                      </div>
                    ))}
                  </div> : <div className="mt-5 border border-dashed border-line bg-bg px-4 py-5 text-sm font-bold text-muted">后台待补充课程模块</div>}
                </section>

                <section className="mt-12 grid gap-8 md:grid-cols-2">
                  <div>
                    <div className="flex items-center gap-2 text-sm font-extrabold text-brand">
                      <BookOpen className="h-4 w-4" />
                      适合人群
                    </div>
                    <p className="mt-3 text-sm leading-7 text-muted">{detailMeta.audience || '后台待补充适合人群'}</p>
                  </div>
                  <div>
                    <div className="flex items-center gap-2 text-sm font-extrabold text-brand">
                      <FileText className="h-4 w-4" />
                      学习权益
                    </div>
                    <p className="mt-3 text-sm leading-7 text-muted">{detailMeta.accessNote || '后台待补充学习权益说明'}</p>
                  </div>
                </section>
              </div>
            </main>

            <aside className="lg:sticky lg:top-[112px]">
              <div className="rounded-[10px] border border-line bg-white p-6 shadow-[0_18px_44px_rgba(15,23,42,0.07)]">
                <div className="text-xs font-bold text-muted">课程价格</div>
                <div className="mt-2 text-4xl font-extrabold text-brand">{offer.price}</div>
                <div className="mt-1 text-sm font-extrabold text-muted">{offer.benefit}</div>

                <div className="my-6 border-t border-line" />

                <div className="space-y-4 text-sm">
                  <div className="flex justify-between gap-6">
                    <span className="text-muted">讲师</span>
                    <span className="font-extrabold text-ink">{course.instructor}</span>
                  </div>
                  <div className="flex justify-between gap-6">
                    <span className="text-muted">课时</span>
                    <span className="font-extrabold text-ink">{course.lessonCount} 课时</span>
                  </div>
                  <div className="flex justify-between gap-6">
                    <span className="text-muted">开课</span>
                    <span className="font-extrabold text-ink">{formatStartDate(startsAt)}</span>
                  </div>
                  <div className="flex justify-between gap-6">
                    <span className="text-muted">形式</span>
                    <span className="font-extrabold text-ink">{course.courseFormat || (course.startsAt ? '直播/线下' : '线上课程')}</span>
                  </div>
                  <div className="flex justify-between gap-6">
                    <span className="text-muted">地点</span>
                    <span className="font-extrabold text-ink">{course.location || '线上'}</span>
                  </div>
                  {isOfflineCourse && (
                    <div className="flex justify-between gap-6">
	                      <span className="text-muted">真实报名</span>
                      <span className="font-extrabold text-ink">{course.registeredCount || 0}/{course.capacity || '不限'}</span>
                    </div>
                  )}
                </div>

                <AddToCartButton
                  item={{
                    id: course.id,
                    type: 'course',
                    title: course.title,
                    price: course.price,
                    href: `/courses/${course.slug}`,
                    meta: `${offer.benefit} · ${course.instructor} · ${course.lessonCount} 课时`,
                  }}
                  label={course.price === 0 ? '加入学习' : '加入购物车'}
                  requiredMembershipLevel={course.memberLevelRequired}
                  membershipAccess={{
                    0: accessForLevel(course, 0),
                    1: accessForLevel(course, 1),
                    2: accessForLevel(course, 2),
                  }}
                  membershipPrices={{
                    0: priceForLevel(course, 0),
                    1: priceForLevel(course, 1),
                    2: priceForLevel(course, 2),
                  }}
                  directOrderOnFree
                  disabled={isFull}
                  disabledLabel="名额已满"
                  className="mt-7 w-full bg-brand py-3 text-white hover:bg-brand-dark"
                />
              </div>
            </aside>
          </div>
        </div>
      </section>
    </>
  )
}
