'use client'

import Link from 'next/link'
import { BookOpen, Clock3, MapPin } from 'lucide-react'
import { useEffect, useState } from 'react'
import { AccountAuthPrompt } from '@/components/account/AccountAuthPrompt'
import { AccountEmptyState } from '@/components/account/AccountEmptyState'
import { useApp } from '@/components/providers/AppProvider'
import { backend, yuan, type BackendCourseProduct, type BackendCourseRegistration } from '@/lib/backend'

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 AccountCoursesPage() {
  const { user, token } = useApp()
  const [courses, setCourses] = useState<BackendCourseProduct[]>([])
  const [registrations, setRegistrations] = useState<BackendCourseRegistration[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    if (!user) return
    setLoading(true)
    void Promise.all([
      backend.courseCatalog(),
      token ? backend.accountCourseRegistrations(token) : Promise.resolve({ items: [] }),
    ]).then(([courseResult, registrationResult]) => {
      setCourses(courseResult.items)
      setRegistrations(registrationResult.items)
      setError('')
    }).catch(() => {
      setCourses([])
      setRegistrations([])
      setError('课程权益加载失败')
    }).finally(() => setLoading(false))
  }, [token, user])

  if (!user) return <AccountAuthPrompt message="登录后可查看已报名课程和学习入口。" />
  if (loading) return <div className="rounded-[4px] border border-line bg-white p-8 text-sm font-bold text-muted">正在加载课程权益...</div>

  const courseEntries = registrations.map((registration) => {
    const course = registration.course || courses.find((courseItem) => courseItem.id === registration.productId || courseItem.slug === registration.productId)
    return { registration, course }
  })
  const offlineCourses = courseEntries.filter(({ course }) => course?.courseFormat === '线下培训')
  const liveCourses = courseEntries.filter(({ course }) => course?.courseFormat === '直播课')
  const unfinishedCourses = courseEntries.filter(({ course }) => course?.startsAt && course.courseStatus !== 'completed' && course.courseFormat !== '线下培训' && course.courseFormat !== '直播课')
  const completedCourses = courseEntries.filter(({ course }) => course?.startsAt && course.courseStatus === 'completed')
  const onlineCourses = courseEntries.filter(({ course }) => !course?.startsAt)

  const renderCourseCards = (entries: typeof courseEntries) => (
    <div className="grid gap-3 md:grid-cols-3 xl:grid-cols-4">
      {entries.map(({ course, registration }) => {
        const priceText = course ? (course.priceAmount > 0 ? `¥${yuan(course.priceAmount)}` : '免费') : ''
        const isOfflineCourse = course?.courseFormat === '线下培训'
        const registrationText = registration ? (registration.status === 'checked_in' ? '已核销' : '待核销') : ''

        return (
          <Link
            key={registration.id}
            href={`/account/courses/${registration.id}`}
            className="block overflow-hidden rounded-[4px] border border-line bg-white shadow-[0_8px_24px_rgba(15,23,42,0.04)] transition hover:border-brand/30 hover:bg-[#f8fbff]"
          >
            <div
              className="relative aspect-[16/8.2] bg-cover bg-center"
              style={{ backgroundImage: course?.coverUrl ? `url(${course.coverUrl})` : 'linear-gradient(135deg,#eef3f8,#dbe6f2)' }}
            >
              <div className="absolute inset-0 bg-[linear-gradient(180deg,rgba(15,23,42,0.05)_0%,rgba(15,23,42,0.22)_100%)]" />
              {!course?.coverUrl && <div className="absolute inset-0 grid place-items-center px-4 text-center text-xs font-extrabold text-muted">暂无课程封面</div>}
            </div>
            <div className="p-3">
              <div className="min-h-10 text-sm font-extrabold leading-5 text-ink">{course?.title || registration.course?.title || registration.productId}</div>
              <div className="mt-3 grid gap-1.5 text-xs text-muted">
                <div className="flex items-center gap-2">
                  <BookOpen className="h-3.5 w-3.5 text-brand" />
                  <span>{course?.courseFormat || '课程'} · {course?.instructor || '授课教师'}</span>
                </div>
                <div className="flex items-center gap-2">
                  <Clock3 className="h-3.5 w-3.5 text-brand" />
                  <span>{course ? `${course.lessonCount} 课时 · ${formatCourseTime(course.startsAt)}` : '课时 · 时间'}</span>
                </div>
                <div className="flex items-center gap-2">
                  <MapPin className="h-3.5 w-3.5 text-brand" />
                  <span>{course?.location || (course?.startsAt ? '线下课程' : '线上课程')}{priceText ? ` · ${priceText}` : ''}</span>
                </div>
                {isOfflineCourse && (
                  <div className="rounded-[4px] bg-bg px-2 py-1 font-extrabold text-brand">
                    线下报名 · {registrationText || '报名已生成'}
                  </div>
                )}
              </div>
            </div>
          </Link>
        )
      })}
    </div>
  )

  return (
    <div>
      {error && <div className="mb-4 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}
      {registrations.length === 0 ? (
        <AccountEmptyState title="暂无课程权益" description="加入免费课程或购买付费课程后，线上课程、未完成课程和已完成课程会分区显示。" actionLabel="浏览课程" actionHref="/courses" />
      ) : (
        <div className="space-y-8">
          {onlineCourses.length > 0 && (
            <section>
              <div className="mb-3 text-sm font-extrabold text-muted">线上课程</div>
              {renderCourseCards(onlineCourses)}
            </section>
          )}
          {liveCourses.length > 0 && (
            <section>
              <div className="mb-3 text-sm font-extrabold text-muted">直播课程</div>
              {renderCourseCards(liveCourses)}
            </section>
          )}
          {offlineCourses.length > 0 && (
            <section>
              <div className="mb-3 text-sm font-extrabold text-muted">线下培训</div>
              {renderCourseCards(offlineCourses)}
            </section>
          )}
          {unfinishedCourses.length > 0 && (
            <section>
              <div className="mb-3 text-sm font-extrabold text-muted">未完成课程</div>
              {renderCourseCards(unfinishedCourses)}
            </section>
          )}
          {completedCourses.length > 0 && (
            <section>
              <div className="mb-3 text-sm font-extrabold text-muted">已完成课程</div>
              {renderCourseCards(completedCourses)}
            </section>
          )}
        </div>
      )}
    </div>
  )
}
