'use client'

import Link from 'next/link'
import { use, useCallback, useEffect, useMemo, useState } from 'react'
import { Download } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendEventProduct, type BackendEventRegistration } from '@/lib/backend'

function statusLabel(status: BackendEventRegistration['status']) {
  if (status === 'pending_payment') return '待支付'
  if (status === 'checked_in') return '已核销'
  if (status === 'waitlisted') return '候补'
  if (status === 'cancel_requested') return '取消申请'
  if (status === 'cancelled') return '已取消'
  if (status === 'no_show') return '未到场'
  if (status === 'refunded') return '已处理'
  return '已报名'
}

function membershipLabel(level?: BackendEventRegistration['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')}`
}

function csvCell(value: unknown) {
  return `"${String(value ?? '').replace(/"/g, '""')}"`
}

export default function AdminEventRegistrationsPage({ params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = use(params)
  const eventId = decodeURIComponent(resolvedParams.id)
  const [event, setEvent] = useState<BackendEventProduct | null>(null)
  const [items, setItems] = useState<BackendEventRegistration[]>([])
  const [selectedId, setSelectedId] = useState('')
  const [status, setStatus] = useState<'all' | BackendEventRegistration['status']>('all')
  const [error, setError] = useState('')
  const [saving, setSaving] = useState(false)

  const reload = useCallback(async (nextStatus: typeof status) => {
    try {
      const [productsResult, registrationsResult] = await Promise.all([
        backend.adminEvents(),
        backend.adminEventRegistrationsForEvent(eventId, { status: nextStatus === 'all' ? '' : nextStatus }),
      ])
      setEvent(productsResult.items.find((item) => item.id === eventId) || null)
      setItems(registrationsResult.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '活动报名加载失败')
    }
  }, [eventId])

  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 pendingPaymentCount = items.filter((item) => item.status === 'pending_payment').length
  const registeredCount = items.filter((item) => item.status === 'registered').length
  const waitlistedCount = items.filter((item) => item.status === 'waitlisted').length
  const checkedCount = items.filter((item) => item.status === 'checked_in').length
  const cancelledCount = items.filter((item) => ['cancelled', 'cancel_requested', 'refunded'].includes(item.status)).length

  async function cancelRegistration(row: BackendEventRegistration) {
    const confirmed = window.confirm(`确定取消 ${row.userName || row.userPhone || row.registrationNo || '该用户'} 的报名吗？已支付订单需要后续人工退款/关闭。`)
    if (!confirmed) return
    setSaving(true)
    try {
      await backend.cancelAdminEventRegistration(row.id, { note: '后台报名管理取消' })
      await reload(status)
    } catch (err) {
      setError(err instanceof Error ? err.message : '取消报名失败')
    } finally {
      setSaving(false)
    }
  }

  function exportCsv() {
    const header = ['报名编号', '姓名', '手机号', '组织', '会员等级', '状态', '订单号', '报名时间', '核销时间', '核销人员']
    const rows = items.map((item) => [
      item.registrationNo || item.id,
      item.userName || '',
      item.userPhone || '',
      item.userOrganization || '',
      membershipLabel(item.membershipLevel),
      statusLabel(item.status),
      item.orderNo || '',
      formatDate(item.createdAt),
      formatDate(item.checkedInAt),
      item.checkedInByStaffName || '',
    ])
    const csv = [header, ...rows].map((row) => row.map(csvCell).join(',')).join('\n')
    const blob = new Blob([`\ufeff${csv}`], { type: 'text/csv;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${event?.slug || eventId}-registrations.csv`
    link.click()
    URL.revokeObjectURL(url)
  }

  return (
    <AdminShell title="活动报名管理" description="查看活动报名名单、用户信息、核销状态，并处理取消和名单导出。">
      <div className="flex h-[calc(100vh-88px)] flex-col gap-2 overflow-hidden">
        <div className="flex shrink-0 flex-wrap items-center justify-between gap-2">
          <Link href="/admin/events" className="text-xs font-extrabold text-brand">返回活动管理</Link>
          <div className="flex flex-wrap gap-2">
            <button type="button" onClick={exportCsv} className="inline-flex h-8 items-center gap-1.5 rounded-[4px] border border-line px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
              <Download className="h-3.5 w-3.5" />
              导出名单
            </button>
            <Link href={`/admin/events/checkin?eventId=${event?.productId || eventId}`} className="inline-flex h-8 items-center rounded-[4px] border border-line px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">进入核销工作台</Link>
            <Link href={`/admin/events/${eventId}/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>
        </div>

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

      <div className="flex min-h-0 flex-1 flex-col border border-line bg-white">
        <div className="grid shrink-0 gap-2 border-b border-line px-3 py-2 text-sm md:grid-cols-[1fr_90px_90px_90px_90px_90px_130px]">
          <div className="min-w-0">
            <div className="truncate text-sm font-extrabold text-ink">{event?.title || eventId}</div>
            <div className="mt-1 truncate text-xs font-bold text-muted">{event?.topic || '-'} · {event?.eventFormat || '-'} · {event?.location || '-'}</div>
          </div>
          <Info label="报名人数" value={items.length} />
          <Info label="待支付" value={pendingPaymentCount} />
          <Info label="已报名" value={registeredCount} />
          <Info label="候补" value={waitlistedCount} />
          <Info label="已核销" value={checkedCount} />
          <Info label="已取消" value={cancelledCount} />
          <Info label="活动时间" value={formatDate(event?.startsAt)} />
        </div>

        <div className="flex shrink-0 flex-wrap items-center gap-2 border-b border-line px-3 py-2">
          {[
            ['all', '全部'],
            ['pending_payment', '待支付'],
            ['registered', '已报名'],
            ['waitlisted', '候补'],
            ['checked_in', '已核销'],
            ['cancelled', '已取消'],
          ].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 min-h-0 flex-1 grid-cols-1 xl:grid-cols-[minmax(0,1fr)_320px]">
          <div className="min-h-0 overflow-auto border-r border-line">
            <div className="min-w-[820px]">
              <div className="sticky top-0 z-10 grid grid-cols-[1fr_100px_90px_120px_130px_110px] border-b border-line bg-white px-3 py-2 text-[11px] font-extrabold text-soft">
                <span>报名人</span><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_100px_90px_120px_130px_110px] items-center border-b border-line px-3 py-2 text-left text-xs 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>
                  <span>
                    {item.status === 'registered' ? (
                      <span onClick={(event) => { event.stopPropagation(); void cancelRegistration(item) }} className={`text-xs font-extrabold text-red-600 ${saving ? 'pointer-events-none opacity-50' : ''}`}>取消报名</span>
                    ) : (
                      <span className="text-xs font-bold text-soft">只读</span>
                    )}
                  </span>
                </button>
              ))}
            </div>
          </div>

          <aside className="min-h-0 overflow-auto p-3">
            <div className="text-xs font-extrabold text-ink">报名人信息</div>
            {selected ? (
              <div className="mt-3 space-y-2 text-xs">
                {[
                  ['报名编号', selected.registrationNo || selected.id],
                  ['姓名', 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-[70px_1fr] gap-2 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>
      </div>
    </AdminShell>
  )
}

function Info({ label, value }: { label: string; value: string | number }) {
  return (
    <div>
      <div className="text-xs font-bold text-muted">{label}</div>
      <div className="mt-1 font-extrabold text-ink">{value}</div>
    </div>
  )
}
