'use client'

import Link from 'next/link'
import { use, useCallback, useEffect, useMemo, useState } from 'react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendCourseProduct, type BackendCourseRegistration } from '@/lib/backend'

function statusLabel(status: BackendCourseRegistration['status']) {
  if (status === 'checked_in') return '已核销'
  if (status === 'cancelled') return '已取消'
  return '未核销'
}

function membershipLabel(level?: BackendCourseRegistration['membershipLevel']) {
  if (level === 'senior') return '高级会员'
  if (level === 'junior') return '初级会员'
  return '注册用户'
}

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

export default function AdminCourseDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = use(params)
  const courseId = decodeURIComponent(resolvedParams.id)
  const [course, setCourse] = useState<BackendCourseProduct | null>(null)
  const [items, setItems] = useState<BackendCourseRegistration[]>([])
  const [selectedId, setSelectedId] = useState('')
  const [status, setStatus] = useState<'all' | BackendCourseRegistration['status']>('all')
  const [error, setError] = useState('')

  const reload = useCallback(async (nextStatus: typeof status) => {
    try {
      const [productsResult, registrationsResult] = await Promise.all([
        backend.adminCourseProducts(),
        backend.adminCourseProductRegistrations(courseId, { status: nextStatus === 'all' ? '' : nextStatus }),
      ])
      setCourse(productsResult.items.find((item) => item.id === courseId) || null)
      setItems(registrationsResult.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '课程报名加载失败')
    }
  }, [courseId])

  useEffect(() => {
    const timer = window.setTimeout(() => { void reload('all') }, 0)
    return () => window.clearTimeout(timer)
  }, [reload])

  const selected = useMemo(() => items.find((item) => item.id === selectedId) || items[0] || null, [items, selectedId])
  const checkedCount = items.filter((item) => item.status === 'checked_in').length
  const capacityText = course?.capacity ? `${items.length}/${course.capacity}` : `${items.length}/不限`

  return (
    <AdminShell title="课程详细" description="查看线下课程报名名单、用户信息和核销状态；后台只查看，不做现场核销。">
      <div className="mb-3 flex items-center justify-between gap-3">
        <Link href="/admin/products/courses" className="text-xs font-extrabold text-brand">返回课程列表</Link>
        <Link href={`/admin/products/courses/${courseId}/edit`} className="inline-flex h-8 items-center rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white hover:bg-brand">编辑课程</Link>
      </div>

      {error && <div className="mb-3 border border-red-200 bg-red-50 px-3 py-2 text-sm font-bold text-red-700">{error}</div>}

      <div className="border border-line bg-white">
        <div className="grid grid-cols-[1fr_110px_110px_150px] gap-3 border-b border-line px-4 py-3 text-sm">
          <div className="min-w-0">
            <div className="truncate text-base font-extrabold text-ink">{course?.title || courseId}</div>
            <div className="mt-1 truncate text-xs font-bold text-muted">{course?.direction || '-'} · {course?.courseFormat || '-'} · {course?.location || '-'}</div>
          </div>
          <div>
            <div className="text-xs font-bold text-muted">报名/名额</div>
            <div className="mt-1 font-extrabold text-ink">{capacityText}</div>
          </div>
          <div>
            <div className="text-xs font-bold text-muted">已核销</div>
            <div className="mt-1 font-extrabold text-ink">{checkedCount}</div>
          </div>
          <div>
            <div className="text-xs font-bold text-muted">开课时间</div>
            <div className="mt-1 font-extrabold text-ink">{formatDate(course?.startsAt)}</div>
          </div>
        </div>

        <div className="flex items-center gap-2 border-b border-line px-4 py-2">
          {[
            ['all', '全部'],
            ['registered', '未核销'],
            ['checked_in', '已核销'],
          ].map(([value, label]) => (
            <button
              key={value}
              type="button"
              onClick={() => {
                setStatus(value as typeof status)
                void reload(value as typeof status)
              }}
              className={`h-7 rounded-full px-3 text-xs font-extrabold ${status === value ? 'bg-ink text-white' : 'bg-bg text-soft hover:text-brand'}`}
            >
              {label}
            </button>
          ))}
        </div>

        <div className="grid grid-cols-[minmax(0,1fr)_320px]">
          <div className="min-h-[360px] border-r border-line">
            <div className="grid grid-cols-[1fr_110px_110px_110px_140px] border-b border-line px-4 py-2 text-xs font-extrabold text-soft">
              <span>报名人</span><span>会员等级</span><span>状态</span><span>订单</span><span>核销时间</span>
            </div>
            {items.length === 0 && <div className="px-4 py-8 text-sm font-bold text-muted">暂无报名记录</div>}
            {items.map((item) => (
              <button
                key={item.id}
                type="button"
                onClick={() => setSelectedId(item.id)}
                className={`grid w-full grid-cols-[1fr_110px_110px_110px_140px] items-center border-b border-line px-4 py-3 text-left text-sm hover:bg-bg ${selected?.id === item.id ? 'bg-bg' : 'bg-white'}`}
              >
                <span className="min-w-0">
                  <span className="block truncate font-extrabold text-ink">{item.userName || '未填写姓名'}</span>
                  <span className="mt-1 block truncate text-xs font-bold text-muted">{item.userPhone || '-'}</span>
                </span>
                <span className="text-xs font-bold text-ink">{membershipLabel(item.membershipLevel)}</span>
                <span className="text-xs font-extrabold text-brand">{statusLabel(item.status)}</span>
                <span className="truncate text-xs font-bold text-muted">{item.orderNo || '-'}</span>
                <span className="text-xs font-bold text-muted">{formatDate(item.checkedInAt)}</span>
              </button>
            ))}
          </div>

          <aside className="p-4">
            <div className="text-sm font-extrabold text-ink">报名人信息</div>
            {selected ? (
              <div className="mt-3 space-y-3 text-sm">
                {[
                  ['姓名', selected.userName || '-'],
                  ['手机号', selected.userPhone || '-'],
                  ['组织', selected.userOrganization || '-'],
                  ['会员等级', membershipLabel(selected.membershipLevel)],
                  ['报名状态', statusLabel(selected.status)],
                  ['核销码', selected.checkinCode],
                  ['订单号', selected.orderNo || '-'],
                  ['报名时间', formatDate(selected.createdAt)],
                  ['核销时间', formatDate(selected.checkedInAt)],
                  ['核销人员', selected.checkedInByStaffName || '-'],
                ].map(([label, value]) => (
                  <div key={label} className="grid grid-cols-[72px_1fr] gap-3 border-b border-line pb-2">
                    <span className="text-xs font-bold text-muted">{label}</span>
                    <span className="break-all font-bold text-ink">{value}</span>
                  </div>
                ))}
              </div>
            ) : (
              <div className="mt-6 text-sm font-bold text-muted">选择左侧报名人查看详情</div>
            )}
          </aside>
        </div>
      </div>
    </AdminShell>
  )
}
