'use client'

import Link from 'next/link'
import { ArrowRight, CalendarDays, ChevronLeft, ChevronRight, MapPin, Users } from 'lucide-react'
import { useState } from 'react'
import { AddToCartButton } from '@/components/commerce/AddToCartButton'
import { ImagePlaceholder } from '@/components/shared/ImagePlaceholder'
import { ScrollReveal } from '@/components/shared/ScrollReveal'
import { useApp } from '@/components/providers/AppProvider'
import type { Event } from '@/types'
import type { BackendRecommendationSlot } from '@/lib/backend'

function getEventMeta(event: Event) {
  return {
    topic: event.topic || '峰会论坛',
    format: event.eventFormat || (event.isOnline ? '线上活动' : '线下活动'),
    cover: event.coverLabel || event.title,
    audience: event.audience || '适合关注数字化转型和数据服务的政企用户参加。',
  }
}

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 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: '报名' }
  return { price: `¥${Math.round((event.registeredPriceAmount || event.price * 100) / 100)}`, priceValue: Math.round((event.registeredPriceAmount || event.price * 100) / 100), benefit: '付费活动', actionLabel: '加入购物车' }
}

function userOfferText(event: Event, membershipLevel: 0 | 1 | 2) {
  const access = membershipLevel === 2 ? event.seniorAccess : membershipLevel === 1 ? event.juniorAccess : event.registeredAccess
  const priceAmount = membershipLevel === 2 ? event.seniorPriceAmount : membershipLevel === 1 ? event.juniorPriceAmount : event.registeredPriceAmount
  if (access === 'closed') return { price: event.memberLevelRequired === 2 ? '高级会员专享' : '会员专享', priceValue: event.price, benefit: '当前等级不可报名', actionLabel: '不可报名' }
  if (access === 'free') return { price: '免费', priceValue: 0, benefit: membershipLevel > 0 ? '会员权益' : '注册后可报名', actionLabel: '报名' }
  return { price: `¥${Math.round((priceAmount || event.price * 100) / 100)}`, priceValue: Math.round((priceAmount || event.price * 100) / 100), benefit: membershipLevel > 0 ? '会员价' : '付费活动', actionLabel: '加入购物车' }
}

export function EventsPageClient({ events, featuredSlots }: { events: Event[]; featuredSlots?: BackendRecommendationSlot[] }) {
  const { user } = useApp()
  const [activeFeatureIndex, setActiveFeatureIndex] = useState(0)

  const hasManagedFeaturedSlots = Array.isArray(featuredSlots)
  const managedFeaturedEvents = hasManagedFeaturedSlots
    ? featuredSlots
      .map((slot) => events.find((event) => event.id === slot.sourceId || event.slug === slot.sourceId))
      .filter((event): event is Event => Boolean(event))
    : null
  const recommendedSource = managedFeaturedEvents ?? events.filter((event) => event.recommended)
  const recommendedEvents = hasManagedFeaturedSlots ? recommendedSource.slice(0, 5) : recommendedSource.slice(0, 3)
  const featuredEvent = recommendedEvents.length ? recommendedEvents[activeFeatureIndex % recommendedEvents.length] : null
  const featuredMeta = featuredEvent ? getEventMeta(featuredEvent) : null
  const featuredOffer = featuredEvent ? (user ? userOfferText(featuredEvent, user.membershipLevel) : offerText(featuredEvent)) : null

  function moveFeatured(step: number) {
    setActiveFeatureIndex((value) => {
      const length = recommendedEvents.length || 1
      return (value + step + length) % length
    })
  }

  function renderEventCard(event: Event) {
	    const meta = getEventMeta(event)
	    const offer = user ? userOfferText(event, user.membershipLevel) : offerText(event)
	    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

    return (
      <article
        key={event.id}
        className="group overflow-hidden rounded-[8px] border border-line bg-white transition hover:-translate-y-1 hover:border-[#b7c4d5] hover:shadow-[0_18px_40px_rgba(15,23,42,0.08)]"
      >
        {event.coverUrl ? (
          <div className="h-40 w-full border-b border-line bg-cover bg-center" style={{ backgroundImage: `url(${event.coverUrl})` }} />
        ) : (
          <ImagePlaceholder label={meta.cover} className="h-40 w-full border-0 border-b border-dashed border-[#9db6d3]" />
        )}
        <div className="p-5">
          <h3 className="min-h-14 text-lg font-extrabold leading-7 text-ink transition-colors group-hover:text-brand">{event.title}</h3>
          <p className="mt-3 line-clamp-2 text-sm leading-6 text-muted">{event.summary}</p>

          <div className="mt-5 space-y-3 border-t border-line pt-4 text-xs text-muted">
            <div className="flex items-start gap-2">
              <CalendarDays className="mt-0.5 h-3.5 w-3.5 text-brand" />
              <div>
                <div className="font-bold">活动时间</div>
                <div className="mt-1 font-extrabold text-ink">{formatEventTime(event.startsAt)}</div>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="flex items-start gap-2">
                <MapPin className="mt-0.5 h-3.5 w-3.5 text-brand" />
                <div className="min-w-0">
                  <div className="font-bold">地点</div>
                  <div className="mt-1 truncate font-extrabold text-ink">{event.isOnline ? '线上直播' : event.location}</div>
                </div>
              </div>
              <div className="flex items-start gap-2">
                <Users className="mt-0.5 h-3.5 w-3.5 text-brand" />
                <div>
	                  <div className="font-bold">报名热度</div>
	                  <div className="mt-1 font-extrabold text-ink">{event.registeredCount || 0}{remaining === null ? ' · 不限名额' : ` · 剩余 ${remaining}`}</div>
                </div>
              </div>
            </div>
          </div>

          <div className="mt-5 flex items-end justify-between gap-4">
            <div>
              <div className="text-xs font-bold text-muted">价格</div>
              <div className="mt-1 text-2xl font-extrabold text-brand">{offer.price}</div>
            </div>
            <div className="flex gap-2">
              <Link href={`/events/${event.slug}`} className="rounded-[4px] border border-line px-4 py-2 text-sm font-bold text-text-body hover:border-brand hover:text-brand">
                详情
              </Link>
              {registrationClosed ? (
                <button type="button" disabled className="inline-flex min-h-10 items-center justify-center rounded-[4px] border border-line bg-bg px-4 py-2 text-sm font-bold text-soft">
                  报名关闭
                </button>
              ) : isFull ? (
                <button type="button" disabled className="inline-flex min-h-10 items-center justify-center rounded-[4px] border border-line bg-bg px-4 py-2 text-sm font-bold text-soft">
                  名额已满
                </button>
              ) : (
                <AddToCartButton
                  item={{
                    id: event.id,
                    type: 'event',
                    title: event.title,
                    price: offer.priceValue,
                    href: `/events/${event.slug}`,
                    meta: `${offer.benefit} · ${formatEventTime(event.startsAt)} · ${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="bg-brand px-4 py-2 text-white hover:bg-brand-dark"
                />
              )}
            </div>
          </div>
        </div>
      </article>
    )
  }

  return (
    <>
      <ScrollReveal />
      <section className="bg-white py-12">
        <div className="mx-auto max-w-[1280px] px-6">
          {featuredEvent ? (
            <div data-reveal="lift" className="overflow-hidden rounded-[12px] border border-line bg-white shadow-[0_24px_70px_rgba(15,23,42,0.08)]">
              <div className="grid md:grid-cols-[0.92fr_1.08fr]">
                {featuredEvent.coverUrl ? (
                  <div className="min-h-[360px] border-r border-line bg-cover bg-center" style={{ backgroundImage: `url(${featuredEvent.coverUrl})` }} />
                ) : (
                  <ImagePlaceholder label={featuredMeta?.cover || `活动封面：${featuredEvent.title}`} className="min-h-[360px] border-0 border-r border-dashed border-[#9db6d3]" />
                )}
                <div className="flex min-h-[360px] flex-col p-8 md:p-10">
                  <div className="mb-8 flex items-center justify-between gap-4">
                    <div>
                      <div className="text-xs font-extrabold text-brand">推荐活动</div>
                    </div>
                    <div className="flex gap-2">
                      <button
                        type="button"
                        onClick={() => moveFeatured(-1)}
                        className="grid h-9 w-9 place-items-center rounded-full border border-line text-muted hover:border-brand hover:text-brand"
                        aria-label="上一场推荐活动"
                      >
                        <ChevronLeft className="h-4 w-4" />
                      </button>
                      <button
                        type="button"
                        onClick={() => moveFeatured(1)}
                        className="grid h-9 w-9 place-items-center rounded-full border border-line text-muted hover:border-brand hover:text-brand"
                        aria-label="下一场推荐活动"
                      >
                        <ChevronRight className="h-4 w-4" />
                      </button>
                    </div>
                  </div>

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

                  <div className="mt-auto grid gap-4 border-t border-line pt-6 text-sm md:grid-cols-3">
                    <div>
                      <div className="text-xs font-bold text-muted">活动时间</div>
                      <div className="mt-1 font-extrabold leading-6 text-ink">{formatEventTime(featuredEvent.startsAt)}</div>
                    </div>
                    <div>
                      <div className="text-xs font-bold text-muted">地点</div>
                      <div className="mt-1 font-extrabold leading-6 text-ink">{featuredEvent.isOnline ? '线上直播' : featuredEvent.location}</div>
                    </div>
                    <div className="flex items-end justify-between gap-4 md:block">
                      <div>
                        <div className="text-xs font-bold text-muted">价格</div>
	                        <div className="mt-1 text-2xl font-extrabold text-brand">{featuredOffer?.price || '免费'}</div>
                      </div>
                      <Link href={`/events/${featuredEvent.slug}`} className="inline-flex items-center gap-2 text-sm font-extrabold text-brand">
                        查看活动 <ArrowRight className="h-4 w-4" />
                      </Link>
                    </div>
                  </div>

                  <div className="mt-7 flex gap-2">
                    {recommendedEvents.map((event, index) => (
                      <button
                        key={event.id}
                        type="button"
                        onClick={() => setActiveFeatureIndex(index)}
                        className={`h-2 rounded-full transition-all ${index === activeFeatureIndex % recommendedEvents.length ? 'w-9 bg-brand' : 'w-2 bg-[#cbd5e1]'}`}
                        aria-label={`切换到第 ${index + 1} 场推荐活动`}
                      />
                    ))}
                  </div>
                </div>
              </div>
            </div>
          ) : !hasManagedFeaturedSlots ? (
            <div data-reveal="lift" className="overflow-hidden rounded-[12px] border border-dashed border-[#b8c4d4] bg-white">
              <div className="grid md:grid-cols-[0.92fr_1.08fr]">
                <div className="grid min-h-[320px] place-items-center border-r border-dashed border-[#d4dce7] bg-[#f3f6fa] px-8 text-center">
                  <div>
                    <div className="text-sm font-extrabold text-brand">暂无推荐活动</div>
                    <div className="mt-3 text-2xl font-extrabold text-ink">暂无可展示项目</div>
                    <p className="mt-4 text-sm leading-7 text-muted">后台配置推荐活动后，这里会展示真实活动内容。</p>
                  </div>
                </div>
                <div className="flex min-h-[320px] flex-col justify-center p-8 md:p-10">
                  <div className="text-xs font-extrabold text-brand">推荐活动</div>
                  <h1 className="mt-6 text-[34px] font-extrabold leading-tight text-ink md:text-[48px]">活动内容待维护</h1>
                  <p className="mt-5 max-w-[700px] text-base leading-8 text-text-body">当前没有已发布且被推荐的活动。后台完成活动标题、时间、地点、名额、价格、封面和详情维护后，这里会显示真实活动。</p>
                </div>
              </div>
            </div>
          ) : null}
        </div>
      </section>

      <section className="bg-[#f7f9fc] py-12">
        <div className="mx-auto max-w-[1280px] px-6">
          <div data-reveal="fade" className="mb-6">
            <div className="text-sm text-muted">共 {events.length} 场活动</div>
            <h2 className="mt-1 text-2xl font-extrabold text-ink">活动目录</h2>
          </div>

          {events.length > 0 ? (
            <div data-reveal-group className="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-3">
              {events.map(renderEventCard)}
            </div>
          ) : (
            <div className="rounded-[8px] border border-line bg-white p-10 text-center">
              <div className="text-lg font-extrabold text-ink">暂无活动</div>
              <p className="mt-3 text-sm text-muted">管理端发布活动后，这里会显示活动目录。</p>
            </div>
          )}
        </div>
      </section>
    </>
  )
}
