'use client'

import Link from 'next/link'
import { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import { CalendarDays, ChevronRight, MapPin } from 'lucide-react'
import { useApp } from '@/components/providers/AppProvider'
import { CheckinQrCode } from '@/components/shared/CheckinQrCode'
import { backend, type BackendEventRegistration } from '@/lib/backend'

function formatDate(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 '已报名'
}

export default function AccountEventPassPage() {
  const params = useParams<{ id: string }>()
  const { user, token } = useApp()
  const [registration, setRegistration] = useState<BackendEventRegistration | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    if (!token || !params.id) return
    let mounted = true
    ;(async () => {
      try {
        const result = await backend.accountEventRegistration(token, params.id)
        if (mounted) setRegistration(result)
      } catch (err) {
        if (mounted) setError(err instanceof Error ? err.message : '报名记录加载失败')
      } finally {
        if (mounted) setLoading(false)
      }
    })()
    return () => {
      mounted = false
    }
  }, [params.id, token])

  if (!user) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center">
          <h1 className="text-2xl font-extrabold text-ink">尚未登录</h1>
          <Link href="/login?redirect=%2Faccount" className="mt-7 inline-flex rounded-[4px] bg-brand px-6 py-3 text-sm font-extrabold text-white">去登录</Link>
        </div>
      </section>
    )
  }

  if (loading) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center">
          <h1 className="text-2xl font-extrabold text-ink">正在加载报名凭证...</h1>
        </div>
      </section>
    )
  }

  if (!registration) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center">
          <h1 className="text-2xl font-extrabold text-ink">暂无报名记录</h1>
          <p className="mt-3 text-sm text-muted">{error || '报名活动后，可在这里查看活动信息和核销凭证。'}</p>
          <Link href="/events" className="mt-7 inline-flex rounded-[4px] bg-brand px-6 py-3 text-sm font-extrabold text-white">浏览活动</Link>
        </div>
      </section>
    )
  }

  const event = registration.event
  const checkedIn = registration.status === 'checked_in'
  const canShowQr = registration.status === 'registered'
  const unavailable = event.status === 'offline' || event.status === 'deleted' || event.productStatus === 'offline'

  return (
    <section className="bg-bg py-8">
      <div className="mx-auto max-w-[1080px] px-6">
        <nav className="mb-6 flex flex-wrap items-center gap-2 text-sm text-muted">
          <Link href="/account/membership" className="hover:text-brand">我的</Link>
          <ChevronRight className="h-4 w-4 text-soft" />
          <Link href="/account/events" className="hover:text-brand">报名活动</Link>
          <ChevronRight className="h-4 w-4 text-soft" />
          <span className="font-bold text-ink">{event.title}</span>
        </nav>

        <div className="grid gap-6 lg:grid-cols-[1fr_300px]">
          <main className="overflow-hidden rounded-[4px] border border-line bg-white shadow-[0_12px_34px_rgba(15,23,42,0.04)]">
            {event.coverUrl ? (
              <div className="aspect-[16/7] bg-cover bg-center" style={{ backgroundImage: `url(${event.coverUrl})` }} />
            ) : (
              <div className="grid aspect-[16/7] place-items-center bg-[#eef3f8] px-8 text-center text-sm font-bold leading-6 text-muted">{event.coverLabel || event.title}</div>
            )}
            <div className="p-7">
              <div className="flex flex-wrap items-center gap-3">
                <h1 className="text-3xl font-extrabold leading-tight text-ink">{event.title}</h1>
                {unavailable && <span className="rounded-[4px] bg-bg px-2.5 py-1 text-xs font-extrabold text-muted">活动已下架</span>}
              </div>
              <p className="mt-4 text-sm leading-8 text-muted">{event.summary}</p>

              <div className="mt-7 grid gap-0.5 overflow-hidden rounded-[4px] bg-line md:grid-cols-2">
                <div className="bg-bg p-4">
                  <div className="flex items-center gap-2 text-xs font-bold text-muted">
                    <CalendarDays className="h-4 w-4 text-brand" />
                    活动时间
                  </div>
                  <div className="mt-2 text-sm font-extrabold text-ink">{event.startsAt ? formatDate(event.startsAt) : '活动时间待确认'}</div>
                </div>
                <div className="bg-bg p-4">
                  <div className="flex items-center gap-2 text-xs font-bold text-muted">
                    <MapPin className="h-4 w-4 text-brand" />
                    地点
                  </div>
                  <div className="mt-2 text-sm font-extrabold text-ink">{event.isOnline ? '线上直播' : event.location}</div>
                </div>
              </div>
            </div>
          </main>

          <aside className="h-fit rounded-[4px] border border-line bg-white p-6 text-center shadow-[0_12px_34px_rgba(15,23,42,0.04)] lg:sticky lg:top-28">
	            <div className="mb-5 text-left">
	              <div className="text-xs font-bold text-muted">报名凭证</div>
	              <div className="mt-1 text-lg font-extrabold text-ink">{registration.checkinCode}</div>
	              {registration.orderNo && <div className="mt-1 text-xs font-bold text-muted">订单 {registration.orderNo}</div>}
	              <div className="mt-2 inline-flex rounded-[4px] bg-brand-light px-2 py-1 text-xs font-extrabold text-brand">{registrationStatusText(registration.status)}</div>
	            </div>
	            {checkedIn ? (
	              <>
                <div className="mx-auto grid h-44 w-44 place-items-center rounded-[6px] bg-green-50">
                  <span className="text-2xl font-extrabold text-green">已核销</span>
                </div>
	                <p className="mt-5 text-sm leading-6 text-muted">该报名记录已完成签到核销。</p>
	              </>
	            ) : canShowQr ? (
	              <>
	                <div className="mx-auto rounded-[8px] border border-line bg-white p-3 shadow-[0_16px_42px_rgba(15,23,42,0.08)]">
	                  <CheckinQrCode value={registration.checkinCode} className="h-44 w-44" />
                </div>
	                <div className="mt-5 text-lg font-extrabold text-ink">核销二维码</div>
	                <p className="mt-2 text-sm leading-6 text-muted">到场签到或线上核销时出示此码，工作人员扫码后完成核销。</p>
	              </>
	            ) : (
	              <>
	                <div className="mx-auto grid h-44 w-44 place-items-center rounded-[6px] bg-bg px-5 text-center">
	                  <span className="text-lg font-extrabold text-muted">{registrationStatusText(registration.status)}</span>
	                </div>
	                <p className="mt-5 text-sm leading-6 text-muted">
	                  {registration.status === 'pending_payment' ? '完成支付后会生成有效核销凭证。' : '当前状态不需要出示核销二维码。'}
	                </p>
	                {registration.status === 'pending_payment' && registration.orderNo && (
	                  <Link href={`/account/orders/${registration.orderNo}`} className="mt-5 inline-flex h-10 items-center rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white">
	                    查看订单
	                  </Link>
	                )}
	              </>
	            )}
	          </aside>
        </div>
      </div>
    </section>
  )
}
