import { notFound } from 'next/navigation'
import type { Metadata } from 'next'
import Link from 'next/link'
import { CalendarDays, ChevronRight, MapPin, Ticket, Users } from 'lucide-react'
import { AddToCartButton } from '@/components/commerce/AddToCartButton'
import { ImagePlaceholder } from '@/components/shared/ImagePlaceholder'
import { getEventProduct } from '@/lib/server-products'
import type { Event } from '@/types'

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params
  const event = await getEventProduct(slug)
  return { title: event ? `${event.title} · 活动报名` : '活动报名' }
}

function offerText(event: Event) {
  const access = event.registeredAccess || (event.memberLevelRequired > 0 ? 'closed' : event.price === 0 ? 'free' : 'paid')
  if (access === 'closed') return { price: '会员专享', priceValue: event.price, benefit: event.memberLevelRequired === 2 ? '高级会员开放' : '会员开放', actionLabel: '会员专享' }
  if (access === 'free') return { price: '免费', priceValue: 0, benefit: '注册后可报名', actionLabel: '立即报名' }
  const priceValue = Math.round((event.registeredPriceAmount || event.price * 100) / 100)
  return { price: `¥${priceValue}`, priceValue, benefit: '付费活动', actionLabel: '加入购物车' }
}

function formatEventDate(value: Date) {
  return `${value.getMonth() + 1}月${value.getDate()}日 ${String(value.getHours()).padStart(2, '0')}:${String(value.getMinutes()).padStart(2, '0')}`
}

export default async function EventDetailPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const event = await getEventProduct(slug)
  if (!event) notFound()
  const start = new Date(event.startsAt)
  const end = new Date(event.endsAt)
  const hasCapacityLimit = event.capacity > 0
  const realRegisteredCount = event.realRegisteredCount ?? Math.max((event.registeredCount || 0) - (event.initialRegisteredCount || 0), 0)
  const isFull = hasCapacityLimit && realRegisteredCount >= event.capacity
  const registrationClosed = event.registrationStatus === 'closed' || event.status === 'registration_closed'
  const remaining = hasCapacityLimit ? Math.max(event.capacity - realRegisteredCount, 0) : null
  const offer = offerText(event)
  const highlights = event.highlights || []
  const agenda = event.agenda || []
  const coverLabel = event.coverLabel || `暂无活动封面：${event.title}`
  const audience = event.audience || ''

  return (
    <section className="border-b border-line bg-[#f7f9fc]">
      <div className="mx-auto max-w-[1280px] px-6 py-10">
        <nav className="mb-8 flex flex-wrap items-center gap-2 text-sm text-muted">
          <Link href="/" className="hover:text-brand">首页</Link>
          <ChevronRight className="h-4 w-4 text-soft" />
          <Link href="/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-8 lg:grid-cols-[1fr_360px] lg:items-start">
          <main className="overflow-hidden rounded-[10px] border border-line bg-white shadow-[0_22px_58px_rgba(15,23,42,0.06)]">
            {event.coverUrl ? (
              <div className="h-[340px] border-b border-line bg-cover bg-center" style={{ backgroundImage: `url(${event.coverUrl})` }} />
            ) : (
              <ImagePlaceholder label={coverLabel} className="h-[340px] border-0 border-b border-dashed border-[#9db6d3]" />
            )}

            <div className="p-8 md:p-10">
              <h1 className="text-[34px] font-extrabold leading-tight text-ink md:text-[48px]">{event.title}</h1>
              <p className="mt-5 max-w-[840px] text-base leading-8 text-text-body">{event.summary}</p>

              <div className="mt-8 grid gap-4 border-y border-line py-5 text-sm md:grid-cols-3">
                <div className="flex gap-3">
                  <CalendarDays className="mt-0.5 h-4 w-4 text-brand" />
                  <div>
                    <div className="text-xs font-bold text-muted">活动时间</div>
                    <div className="mt-1 font-extrabold text-ink">{formatEventDate(start)}-{String(end.getHours()).padStart(2, '0')}:{String(end.getMinutes()).padStart(2, '0')}</div>
                  </div>
                </div>
                <div className="flex gap-3">
                  <MapPin className="mt-0.5 h-4 w-4 text-brand" />
                  <div>
                    <div className="text-xs font-bold text-muted">地点</div>
                    <div className="mt-1 font-extrabold text-ink">{event.isOnline ? '线上直播' : event.location}</div>
                  </div>
                </div>
                <div className="flex gap-3">
                  <Users className="mt-0.5 h-4 w-4 text-brand" />
                  <div>
                    <div className="text-xs font-bold text-muted">报名热度</div>
                    <div className="mt-1 font-extrabold text-ink">{event.registeredCount || 0}{remaining === null ? ' · 不限名额' : isFull ? ' · 已满员' : ` · 剩余 ${remaining}`}</div>
                  </div>
                </div>
              </div>

              <section className="mt-10">
                <h2 className="text-2xl font-extrabold text-ink">活动亮点</h2>
                {highlights.length ? <div className="mt-5 grid gap-x-8 gap-y-4 md:grid-cols-2">
                  {highlights.map((item, index) => (
                    <div key={item} className="flex gap-3 border-t border-line pt-4">
                      <span className="text-xs font-extrabold text-soft">0{index + 1}</span>
                      <span className="text-sm font-bold leading-7 text-text-body">{item}</span>
                    </div>
                  ))}
                </div> : <div className="mt-5 border border-dashed border-line bg-bg px-4 py-5 text-sm font-bold text-muted">后台待补充活动亮点</div>}
              </section>

              <section className="mt-12">
                <h2 className="text-2xl font-extrabold text-ink">活动安排</h2>
                {agenda.length ? <div className="mt-5 divide-y divide-line border-y border-line">
                  {agenda.map((item, index) => (
                    <div key={item} className="grid gap-4 py-5 md:grid-cols-[92px_1fr]">
                      <div className="text-sm font-extrabold text-brand">环节 {index + 1}</div>
                      <div className="font-extrabold text-ink">{item}</div>
                    </div>
                  ))}
                </div> : <div className="mt-5 border border-dashed border-line bg-bg px-4 py-5 text-sm font-bold text-muted">后台待补充活动安排</div>}
              </section>

              <section className="mt-12">
                <div className="flex items-center gap-2 text-sm font-extrabold text-brand">
                  <Ticket className="h-4 w-4" />
                  适合人群
                </div>
                <p className="mt-3 text-sm leading-7 text-muted">{audience || '后台待补充适合人群'}</p>
              </section>
            </div>
          </main>

          <aside className="lg:sticky lg:top-[112px]">
            <div className="rounded-[10px] border border-line bg-white p-6 shadow-[0_18px_44px_rgba(15,23,42,0.07)]">
              <div className="text-xs font-bold text-muted">报名费用</div>
              <div className="mt-2 text-4xl font-extrabold text-brand">{offer.price}</div>
              <div className="mt-1 text-sm font-extrabold text-muted">{offer.benefit}</div>

              <div className="my-6 border-t border-line" />

              <div className="space-y-4 text-sm">
                <div className="flex justify-between gap-6">
                  <span className="text-muted">时间</span>
                  <span className="font-extrabold text-ink">{formatEventDate(start)}</span>
                </div>
                <div className="flex justify-between gap-6">
                  <span className="text-muted">地点</span>
                  <span className="font-extrabold text-ink">{event.isOnline ? '线上直播' : event.location}</span>
                </div>
                <div className="flex justify-between gap-6">
                  <span className="text-muted">报名热度</span>
                  <span className="font-extrabold text-ink">{event.registeredCount || 0}{remaining === null ? ' · 不限名额' : isFull ? ' · 已满员' : ` · 剩余 ${remaining}`}</span>
                </div>
              </div>

              {registrationClosed ? (
                <button type="button" disabled className="mt-7 w-full rounded-[4px] border border-line bg-bg py-3 text-sm font-extrabold text-soft">报名已关闭</button>
              ) : isFull ? (
                <button type="button" disabled className="mt-7 w-full rounded-[4px] border border-line bg-bg py-3 text-sm font-extrabold text-soft">名额已满</button>
              ) : (
                <AddToCartButton
                  item={{
                    id: event.id,
                    type: 'event',
                    title: event.title,
                    price: offer.priceValue,
                    href: `/events/${event.slug}`,
                    meta: `${offer.benefit} · ${formatEventDate(start)} · ${event.isOnline ? '线上直播' : event.location}`,
                  }}
                  label={offer.actionLabel}
                  requiredMembershipLevel={event.memberLevelRequired}
                  membershipAccess={{
                    0: event.registeredAccess,
                    1: event.juniorAccess,
                    2: event.seniorAccess,
                  }}
                  membershipPrices={{
                    0: Math.round((event.registeredPriceAmount || 0) / 100),
                    1: Math.round((event.juniorPriceAmount || 0) / 100),
                    2: Math.round((event.seniorPriceAmount || 0) / 100),
                  }}
                  directOrderOnFree
                  className="mt-7 w-full bg-brand py-3 text-white hover:bg-brand-dark"
                />
              )}
            </div>
          </aside>
        </div>
      </div>
    </section>
  )
}
