'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { CalendarDays, Plus, Search, UsersRound } from 'lucide-react'
import { AdminMetricPanel } from '@/components/admin/AdminMetrics'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendEventProduct, yuan } from '@/lib/backend'
import type { CourseAccessState } from '@/types'

function safeCents(value: unknown) {
  return Number.isFinite(Number(value)) ? Number(value) : 0
}

function statusLabel(status: string, registrationStatus?: string) {
  if (status === 'registration_closed') return '报名关闭'
  if (registrationStatus === 'full') return '名额已满'
  if (registrationStatus === 'finished') return '已结束'
  if (status === 'published') return '报名开放'
  if (status === 'offline') return '已下线'
  return '草稿'
}

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

function accessLabel(access: CourseAccessState, priceAmount: number) {
  if (access === 'closed') return '不可报名'
  if (access === 'free') return '免费'
  return `¥${yuan(safeCents(priceAmount))}`
}

function accessSummary(item: BackendEventProduct) {
  return [
    `注册 ${accessLabel(item.registeredAccess, item.registeredPriceAmount)}`,
    `初级 ${accessLabel(item.juniorAccess, item.juniorPriceAmount)}`,
    `高级 ${accessLabel(item.seniorAccess, item.seniorPriceAmount)}`,
  ].join(' / ')
}

export function EventManagementPage() {
  const [items, setItems] = useState<BackendEventProduct[]>([])
  const [keyword, setKeyword] = useState('')
  const [statusFilter, setStatusFilter] = useState('')
  const [error, setError] = useState('')
  const visibleItems = useMemo(() => {
    const words = keyword.trim().toLowerCase()
    return items.filter((item) => {
      const statusMatched = !statusFilter || item.status === statusFilter || item.registrationStatus === statusFilter
      if (!statusMatched) return false
      if (!words) return true
      return [item.title, item.slug, item.topic, item.eventFormat, item.location].some((value) => String(value || '').toLowerCase().includes(words))
    })
  }, [items, keyword, statusFilter])
  const stats = useMemo(() => ({
    total: items.length,
    published: items.filter((item) => item.status === 'published').length,
    closed: items.filter((item) => item.status === 'registration_closed' || item.registrationStatus === 'closed').length,
    registrations: items.reduce((sum, item) => sum + Number(item.realRegisteredCount ?? item.registrationStats?.total ?? item.registeredCount ?? 0), 0),
    checkedIn: items.reduce((sum, item) => sum + Number(item.checkedInCount || item.registrationStats?.checkedIn || 0), 0),
  }), [items])

  async function reload() {
    await backend.adminEvents()
      .then((result) => setItems(result.items))
      .catch((err) => setError(err instanceof Error ? err.message : '活动加载失败'))
  }

  useEffect(() => { void reload() }, [])

  async function changeStatus(id: string, action: 'publish' | 'offline' | 'close' | 'delete') {
    try {
      if (action === 'publish') await backend.publishEvent(id)
      if (action === 'offline') await backend.offlineEvent(id)
      if (action === 'close') await backend.closeEventRegistration(id)
      if (action === 'delete') {
        const confirmed = window.confirm('确定下线这个活动吗？已有报名记录会保留，用户端不再展示。')
        if (!confirmed) return
        await backend.deleteEvent(id)
      }
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '操作失败')
    }
  }

  return (
    <AdminShell title="活动管理" description="维护活动展示、报名规则、名单统计和现场核销入口。活动仍由订单系统承载支付，但后台按活动运营组织。">
      <div className="flex h-[calc(100vh-88px)] flex-col gap-2 overflow-hidden">
        <AdminMetricPanel
          items={[
            { label: '活动总数', value: stats.total },
            { label: '开放报名', value: stats.published },
            { label: '报名关闭', value: stats.closed },
            { label: '报名人数', value: stats.registrations },
            { label: '已核销', value: stats.checkedIn },
          ]}
        />

        <section className="grid shrink-0 gap-2 border border-line bg-white p-2 lg:grid-cols-[150px_minmax(0,1fr)_auto_auto]">
          <select value={statusFilter} onChange={(event) => setStatusFilter(event.target.value)} className="h-8 border border-line px-2 text-xs font-bold">
            <option value="">全部活动</option>
            <option value="published">报名开放</option>
            <option value="registration_closed">报名关闭</option>
            <option value="full">名额已满</option>
            <option value="finished">已结束</option>
            <option value="draft">草稿</option>
            <option value="offline">已下线</option>
          </select>
          <div className="flex h-8 min-w-0 items-center border border-line px-2.5 focus-within:border-brand">
            <Search className="h-3.5 w-3.5 text-soft" />
            <input value={keyword} onChange={(event) => setKeyword(event.target.value)} placeholder="搜索标题、主题、形式、地点" className="min-w-0 flex-1 px-2 text-xs font-bold outline-none" />
          </div>
          <div className="hidden items-center gap-2 text-[11px] font-bold text-muted xl:flex">
            <span className="inline-flex items-center gap-1"><CalendarDays className="h-3.5 w-3.5 text-brand" />展示/报名</span>
            <span className="inline-flex items-center gap-1"><UsersRound className="h-3.5 w-3.5 text-brand" />名单/核销</span>
          </div>
          <Link href="/admin/events/new" className="inline-flex h-8 items-center justify-center gap-1.5 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white hover:bg-brand">
            <Plus className="h-3.5 w-3.5" />
            新增活动
          </Link>
        </section>

        <div className="min-h-0 flex-1 overflow-hidden border border-line bg-white">
          <div className="h-full overflow-auto">
            <div className="min-w-[1260px]">
              <div className="sticky top-0 z-10 grid grid-cols-[minmax(260px,1fr)_120px_220px_210px_180px_230px] 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>
              {error && <div className="px-4 py-4 text-sm font-bold text-red-700">{error}</div>}
              {visibleItems.map((item) => (
                <div key={item.id} className="grid grid-cols-[minmax(260px,1fr)_120px_220px_210px_180px_230px] items-center border-b border-line px-3 py-2 text-xs hover:bg-bg">
                  <div className="min-w-0">
                    <div className="truncate font-extrabold text-ink">{item.title}</div>
                    <div className="mt-0.5 truncate text-[11px] font-bold text-muted">{item.slug}{item.recommended ? ' · 推荐' : ''}</div>
                    <div className="mt-0.5 truncate text-[11px] text-soft">{item.location || (item.isOnline ? '线上活动' : '-')}</div>
                  </div>
                  <span className="text-[11px] font-bold leading-5 text-muted">{item.topic}<br />{item.eventFormat}</span>
                  <span className="text-[11px] font-bold leading-5 text-ink">{accessSummary(item)}</span>
                  <span className="text-[11px] font-bold leading-5 text-muted">
                    {formatStart(item.startsAt)}<br />
                    报名 {item.realRegisteredCount ?? item.registrationStats?.total ?? item.registeredCount ?? 0}/{item.capacity || '不限'} · 候补 {item.registrationStats?.waitlisted || 0} · 核销 {item.checkedInCount || item.registrationStats?.checkedIn || 0}
                  </span>
                  <span className="text-[11px] font-bold leading-5 text-muted">
                    <span className="font-extrabold text-brand">{statusLabel(item.status, item.registrationStatus)}</span><br />
                    表单 {item.formSchema?.length || 0} 项 · 取消 {item.registrationStats?.cancelled || 0}
                  </span>
                  <div className="flex flex-wrap gap-x-2 gap-y-1">
                    <Link href={`/admin/events/${item.id}/registrations`} className="text-xs font-extrabold text-brand">报名名单</Link>
                    <Link href={`/admin/events/checkin?eventId=${item.productId || item.id}`} className="text-xs font-extrabold text-brand">核销</Link>
                    <Link href={`/admin/events/${item.id}/edit`} className="text-xs font-extrabold text-brand">编辑</Link>
                    {item.status !== 'published' && <button type="button" onClick={() => void changeStatus(item.id, 'publish')} className="text-xs font-extrabold text-ink">{item.status === 'registration_closed' ? '重新开放' : '发布'}</button>}
                    {item.status === 'published' && <button type="button" onClick={() => void changeStatus(item.id, 'close')} className="text-xs font-extrabold text-ink">关闭报名</button>}
                    {item.status === 'published' && <button type="button" onClick={() => void changeStatus(item.id, 'offline')} className="text-xs font-extrabold text-ink">下线</button>}
                    <button type="button" onClick={() => void changeStatus(item.id, 'delete')} className="text-xs font-extrabold text-red-600">删除</button>
                  </div>
                </div>
              ))}
              {!visibleItems.length && !error && <div className="px-4 py-10 text-center text-sm font-bold text-muted">暂无活动</div>}
            </div>
          </div>
        </div>
      </div>
    </AdminShell>
  )
}
