'use client'

import Link from 'next/link'
import { ArrowRight, CalendarDays, ChevronLeft, ChevronRight, Clock3, MapPin, UserRound, Users } from 'lucide-react'
import { useState } from 'react'
import { AddToCartButton } from '@/components/commerce/AddToCartButton'
import { ImagePlaceholder } from '@/components/shared/ImagePlaceholder'
import { ScrollReveal } from '@/components/shared/ScrollReveal'
import type { Course } from '@/types'
import type { BackendRecommendationSlot } from '@/lib/backend'

type DirectionFilter = '全部' | '数据治理' | 'AI应用' | '数字化转型' | '政策解读' | '企业实训'
type FormatFilter = '全部' | '线上课程' | '直播课' | '线下培训'

const courseMeta: Record<string, { direction: DirectionFilter; format: FormatFilter; audience: string; cover: string }> = {
  'data-governance-fundamentals': {
    direction: '数据治理',
    format: '直播课',
    audience: '数据负责人、治理专员、业务骨干',
    cover: '数据治理课程封面：资产盘点、标准管理与质量规则工作台',
  },
  'smart-city-planning': {
    direction: '数字化转型',
    format: '线上课程',
    audience: '政府信息化、园区运营与项目规划人员',
    cover: '智慧城市课程封面：城市数字底座、治理场景与规划蓝图',
  },
  'llm-government-applications': {
    direction: 'AI应用',
    format: '直播课',
    audience: '政务服务、审批管理、数字化平台主管',
    cover: 'AI应用课程封面：政务大模型、智能办理与协同办公场景',
  },
  'industrial-internet-transformation': {
    direction: '企业实训',
    format: '线上课程',
    audience: '制造企业管理层、信息化部门与车间负责人',
    cover: '制造业数字化课程封面：生产现场、工业互联网与转型路径',
  },
  'data-platform-architecture': {
    direction: '数据治理',
    format: '直播课',
    audience: '数据平台负责人、架构师、数据工程团队',
    cover: '数据平台课程封面：数据中台、湖仓一体与架构设计',
  },
  'digital-economy-policy': {
    direction: '政策解读',
    format: '线上课程',
    audience: '企业战略、园区服务、政策研究与申报人员',
    cover: '政策解读课程封面：数字经济政策、企业策略与机会清单',
  },
}

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

function getCourseMeta(course: Course) {
  const fallback = courseMeta[course.slug] || {
    direction: '企业实训' as DirectionFilter,
    format: course.startsAt ? ('直播课' as FormatFilter) : ('线上课程' as FormatFilter),
    audience: '政企数字化相关岗位',
    cover: `暂无课程封面：${course.title}`,
  }
  return {
    direction: (course.direction || fallback.direction) as DirectionFilter,
    format: (course.courseFormat || fallback.format) as FormatFilter,
    audience: course.audience || fallback.audience,
    cover: fallback.cover,
  }
}

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 values = ([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 values.length ? Math.min(...values) : 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: '全员免费', tone: 'green' }
  if (registered === 'paid' && junior === 'free' && senior === 'free') return { price: priceText, benefit: '会员免费，注册用户付费', tone: 'brand' }
  if (registered === 'closed' && junior === 'free' && senior === 'free') return { price: priceText, benefit: '会员免费，注册用户不开放', tone: 'brand' }
  if (registered === 'closed' && junior === 'paid' && senior === 'free') return { price: priceText, benefit: '初级收费，高级免费', tone: 'gold' }
  if (registered === 'closed' && junior === 'closed' && senior !== 'closed') return { price: priceText, benefit: senior === 'free' ? '仅高级会员免费' : '仅高级会员收费开放', tone: 'gold' }
  if (registered === 'paid' || junior === 'paid' || senior === 'paid') return { price: priceText, benefit: '分身份定价', tone: 'plain' }
  return { price: priceText, benefit: '限指定身份开放', tone: 'brand' }
}

export function CoursesPageClient({ courses, featuredSlots }: { courses: Course[]; featuredSlots?: BackendRecommendationSlot[] }) {
  const [activeFeatureIndex, setActiveFeatureIndex] = useState(0)

  const hasManagedFeaturedSlots = Array.isArray(featuredSlots)
  const managedFeaturedCourses = hasManagedFeaturedSlots
    ? featuredSlots
      .map((slot) => courses.find((course) => course.id === slot.sourceId || course.slug === slot.sourceId))
      .filter((course): course is Course => Boolean(course))
    : null
  const recommendedItems = managedFeaturedCourses ?? courses.filter((course) => course.recommended)
  const recommendedCourses = hasManagedFeaturedSlots
    ? recommendedItems.slice(0, 5)
    : (recommendedItems.length ? recommendedItems : courses).slice(0, Math.min(courses.length, 4))
  const featuredCourse = recommendedCourses.length ? recommendedCourses[activeFeatureIndex % recommendedCourses.length] : null
  const featuredMeta = featuredCourse ? getCourseMeta(featuredCourse) : null
  const featuredOffer = featuredCourse ? offerText(featuredCourse) : null

  function moveFeatured(step: number) {
    setActiveFeatureIndex((value) => {
      const length = recommendedCourses.length || 1
      return (value + step + length) % length
    })
  }

  function renderCourseCard(course: Course) {
    const meta = getCourseMeta(course)
    const offer = offerText(course)
    const isOfflineCourse = course.courseFormat === '线下培训'
    const isFull = isOfflineCourse && Boolean(course.capacity && (course.registeredCount || 0) >= course.capacity)

    return (
      <article
        key={course.id}
        className="group overflow-hidden rounded-[8px] border border-line bg-white transition hover:-translate-y-1 hover:border-[#b7c4d5] hover:shadow-[0_18px_40px_rgba(15,23,42,0.08)]"
      >
        {course.coverUrl ? (
          <div className="h-40 w-full border-b border-line bg-cover bg-center" style={{ backgroundImage: `url(${course.coverUrl})` }} />
        ) : (
          <ImagePlaceholder label={meta.cover} className="h-40 w-full border-0 border-b border-dashed border-[#9db6d3]" />
        )}
        <div className="p-5">
          <h3 className="min-h-14 text-lg font-extrabold leading-7 text-ink transition-colors group-hover:text-brand">{course.title}</h3>
          <p className="mt-3 line-clamp-2 text-sm leading-6 text-muted">{course.summary}</p>

          <div className="mt-5 grid grid-cols-2 gap-3 border-t border-line pt-4 text-xs text-muted">
            <div>
              <div className="flex items-center gap-1.5 font-bold">
                <CalendarDays className="h-3.5 w-3.5" />
                开课
              </div>
              <div className="mt-1 font-extrabold text-ink">{formatDate(course.startsAt)}</div>
            </div>
            <div>
              <div className="flex items-center gap-1.5 font-bold">
                <Clock3 className="h-3.5 w-3.5" />
                课时
              </div>
              <div className="mt-1 font-extrabold text-ink">{course.lessonCount} 课时</div>
            </div>
            <div>
              <div className="flex items-center gap-1.5 font-bold">
                <UserRound className="h-3.5 w-3.5" />
                讲师
              </div>
              <div className="mt-1 truncate font-extrabold text-ink">{course.instructor}</div>
            </div>
            <div>
              <div className="flex items-center gap-1.5 font-bold">
                <MapPin className="h-3.5 w-3.5" />
                地点/形式
              </div>
              <div className="mt-1 truncate font-extrabold text-ink">{course.location || '线上'} · {course.courseFormat || '课程'}</div>
            </div>
          </div>

          <div className="mt-5 flex items-end justify-between gap-4">
            <div>
              <div className="text-xs font-bold text-muted">价格</div>
              <div className="mt-1 text-2xl font-extrabold text-brand">{offer.price}</div>
              {isOfflineCourse && (
                <div className="mt-1 flex items-center gap-1 text-xs font-bold text-muted">
                  <Users className="h-3.5 w-3.5" />
	                  真实报名 {course.registeredCount || 0}/{course.capacity || '不限'}
                </div>
              )}
            </div>
            <div className="flex gap-2">
              <Link href={`/courses/${course.slug}`} className="rounded-[4px] border border-line px-4 py-2 text-sm font-bold text-text-body hover:border-brand hover:text-brand">
                详情
              </Link>
              <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="bg-brand px-4 py-2 text-white hover:bg-brand-dark"
              />
            </div>
          </div>
        </div>
      </article>
    )
  }

  return (
    <>
      <ScrollReveal />
      <section className="bg-white py-12">
        <div className="mx-auto max-w-[1280px] px-6">
          {featuredCourse && (
            <div data-reveal="lift" className="overflow-hidden rounded-[12px] border border-line bg-white shadow-[0_24px_70px_rgba(15,23,42,0.08)]">
              <div className="grid md:grid-cols-[0.92fr_1.08fr]">
                {featuredCourse.coverUrl ? (
                  <div className="min-h-[360px] border-r border-line bg-cover bg-center" style={{ backgroundImage: `url(${featuredCourse.coverUrl})` }} />
                ) : (
                  <ImagePlaceholder label={featuredMeta?.cover || '暂无课程封面'} className="min-h-[360px] border-0 border-r border-dashed border-[#9db6d3]" />
                )}
                <div className="flex min-h-[360px] flex-col p-8 md:p-10">
                  <div className="mb-8 flex items-center justify-between gap-4">
                    <div>
                      <div className="text-xs font-extrabold text-brand">推荐课程</div>
                    </div>
                    <div className="flex gap-2">
                      <button
                        type="button"
                        onClick={() => moveFeatured(-1)}
                        className="grid h-9 w-9 place-items-center rounded-full border border-line text-muted hover:border-brand hover:text-brand"
                        aria-label="上一门推荐课程"
                      >
                        <ChevronLeft className="h-4 w-4" />
                      </button>
                      <button
                        type="button"
                        onClick={() => moveFeatured(1)}
                        className="grid h-9 w-9 place-items-center rounded-full border border-line text-muted hover:border-brand hover:text-brand"
                        aria-label="下一门推荐课程"
                      >
                        <ChevronRight className="h-4 w-4" />
                      </button>
                    </div>
                  </div>

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

                  <div className="mt-auto grid gap-4 border-t border-line pt-6 text-sm md:grid-cols-3">
                    <div>
                      <div className="text-xs font-bold text-muted">适合对象</div>
                      <div className="mt-1 font-extrabold leading-6 text-ink">{featuredMeta?.audience}</div>
                    </div>
                    <div>
                      <div className="text-xs font-bold text-muted">课时</div>
                      <div className="mt-1 font-extrabold text-ink">{featuredCourse.lessonCount} 课时</div>
                    </div>
                    <div className="flex items-end justify-between gap-4 md:block">
                      <div>
                        <div className="text-xs font-bold text-muted">价格</div>
                        <div className="mt-1 text-2xl font-extrabold text-brand">{featuredOffer?.price}</div>
                      </div>
                      <Link href={`/courses/${featuredCourse.slug}`} className="inline-flex items-center gap-2 text-sm font-extrabold text-brand">
                        查看课程 <ArrowRight className="h-4 w-4" />
                      </Link>
                    </div>
                  </div>

                  <div className="mt-7 flex gap-2">
                    {recommendedCourses.map((course, index) => (
                      <button
                        key={course.id}
                        type="button"
                        onClick={() => setActiveFeatureIndex(index)}
                        className={`h-2 rounded-full transition-all ${index === activeFeatureIndex % recommendedCourses.length ? 'w-9 bg-brand' : 'w-2 bg-[#cbd5e1]'}`}
                        aria-label={`切换到第 ${index + 1} 门推荐课程`}
                      />
                    ))}
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </section>

      <section className="bg-[#f7f9fc] py-12">
        <div className="mx-auto max-w-[1280px] px-6">
          <div data-reveal="fade" className="mb-6 flex items-end justify-between gap-4">
            <div>
              <div className="text-sm text-muted">共 {courses.length} 门课程</div>
              <h2 className="mt-1 text-2xl font-extrabold text-ink">课程目录</h2>
            </div>
          </div>

          {courses.length > 0 ? (
            <div data-reveal-group className="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-3">
              {courses.map(renderCourseCard)}
            </div>
          ) : (
            <div className="rounded-[8px] border border-line bg-white p-10 text-center">
              <div className="text-lg font-extrabold text-ink">暂无课程</div>
              <p className="mt-3 text-sm text-muted">管理端发布课程后，这里会显示课程目录。</p>
            </div>
          )}
        </div>
      </section>
    </>
  )
}
