'use client'

import Link from 'next/link'
import { useEffect, useState } from 'react'
import { CalendarDays, MapPin, QrCode } from 'lucide-react'
import { AccountAuthPrompt } from '@/components/account/AccountAuthPrompt'
import { AccountEmptyState } from '@/components/account/AccountEmptyState'
import { useApp } from '@/components/providers/AppProvider'
import { backend, type BackendEventRegistration } from '@/lib/backend'

function formatEventTime(value: string) {
  const date = new Date(value)
  return `${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

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

function registrationStatusTone(status: BackendEventRegistration['status']) {
  if (status === 'checked_in') return 'bg-green-50 text-green'
  if (status === 'cancelled' || status === 'refunded' || status === 'no_show') return 'bg-bg text-muted'
  if (status === 'pending_payment' || status === 'waitlisted' || status === 'cancel_requested') return 'bg-amber-50 text-amber-700'
  return 'bg-brand-light text-brand'
}

export default function AccountEventsPage() {
  const { user, token } = useApp()
  const [items, setItems] = useState<BackendEventRegistration[]>([])
  const [error, setError] = useState('')

  useEffect(() => {
    if (!token) return
    let mounted = true
    ;(async () => {
      try {
        const result = await backend.accountEventRegistrations(token)
        if (mounted) setItems(result.items)
      } catch (err) {
        if (mounted) setError(err instanceof Error ? err.message : '活动报名记录加载失败')
      }
    })()
    return () => {
      mounted = false
    }
  }, [token])

  if (!user) return <AccountAuthPrompt message="登录后可查看活动报名记录和核销信息。" />

  const eventItems = items.sort((a, b) => new Date(a.event.startsAt || a.createdAt).getTime() - new Date(b.event.startsAt || b.createdAt).getTime())
  const pendingPaymentItems = eventItems.filter((entry) => entry.status === 'pending_payment')
  const registeredItems = eventItems.filter((entry) => entry.status === 'registered')
  const waitlistedItems = eventItems.filter((entry) => entry.status === 'waitlisted')
  const checkedItems = eventItems.filter((entry) => entry.status === 'checked_in')
  const cancelledItems = eventItems.filter((entry) => ['cancel_requested', 'cancelled', 'no_show', 'refunded'].includes(entry.status))

  const renderEventCards = (items: BackendEventRegistration[]) => (
    <div className="grid gap-3 md:grid-cols-3 xl:grid-cols-4">
      {items.map((registration) => {
        const event = registration.event
        const checkedIn = registration.status === 'checked_in'

        return (
          <article key={registration.id} className="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]">
            <Link href={`/account/events/${registration.id}`} className="block">
              {event.coverUrl ? (
                <div className="relative aspect-[16/8.2] bg-cover bg-center" style={{ backgroundImage: `url(${event.coverUrl})` }}>
                  <div className="absolute inset-0 bg-[linear-gradient(180deg,rgba(15,23,42,0.05)_0%,rgba(15,23,42,0.24)_100%)]" />
                </div>
              ) : (
                <div className="grid aspect-[16/8.2] place-items-center bg-[#eef3f8] px-5 text-center text-xs font-bold leading-5 text-muted">{event.coverLabel || event.title}</div>
              )}
              <div className="p-3">
                <div className="flex min-h-10 items-start justify-between gap-2">
                  <div className="text-sm font-extrabold leading-5 text-ink">{event.title}</div>
	                  <span className={`shrink-0 rounded-[4px] px-2.5 py-1 text-xs font-extrabold ${registrationStatusTone(registration.status)}`}>
	                    {registrationStatusText(registration.status)}
	                  </span>
                </div>
                <div className="mt-3 grid gap-1.5 text-xs text-muted">
                  <div className="flex items-center gap-2">
                    <CalendarDays className="h-3.5 w-3.5 text-brand" />
                    {event.startsAt ? formatEventTime(event.startsAt) : '活动时间'}
                  </div>
                  <div className="flex items-center gap-2">
                    <MapPin className="h-3.5 w-3.5 text-brand" />
                    {event.isOnline ? '线上直播' : event.location || '活动地点'}
                  </div>
                  <div className="flex items-center gap-2">
                    <QrCode className="h-3.5 w-3.5 text-brand" />
	                    {checkedIn ? '已完成签到核销' : registration.status === 'pending_payment' ? '待支付后生成有效凭证' : registration.status === 'registered' ? '查看核销信息' : registrationStatusText(registration.status)}
                  </div>
                </div>
              </div>
            </Link>
          </article>
        )
      })}
    </div>
  )

  return (
    <div>
      {error && <div className="mb-4 rounded-[4px] border border-red-200 bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}
      {eventItems.length === 0 ? (
        <AccountEmptyState title="暂无活动报名" description="报名峰会、沙龙或研讨会后，活动信息和核销状态会在这里显示。" actionLabel="浏览活动" actionHref="/events" />
      ) : (
        <div className="space-y-8">
	          {pendingPaymentItems.length > 0 && (
	            <section>
	              <div className="mb-3 text-sm font-extrabold text-muted">待支付</div>
	              {renderEventCards(pendingPaymentItems)}
	            </section>
	          )}
	          {registeredItems.length > 0 && (
	            <section>
	              <div className="mb-3 text-sm font-extrabold text-muted">已报名</div>
	              {renderEventCards(registeredItems)}
	            </section>
	          )}
	          {waitlistedItems.length > 0 && (
	            <section>
	              <div className="mb-3 text-sm font-extrabold text-muted">候补中</div>
	              {renderEventCards(waitlistedItems)}
	            </section>
	          )}
          {checkedItems.length > 0 && (
            <section>
              <div className="mb-3 text-sm font-extrabold text-muted">已核销</div>
	              {renderEventCards(checkedItems)}
	            </section>
	          )}
	          {cancelledItems.length > 0 && (
	            <section>
	              <div className="mb-3 text-sm font-extrabold text-muted">已取消/已关闭</div>
	              {renderEventCards(cancelledItems)}
	            </section>
	          )}
        </div>
      )}
    </div>
  )
}
