import { useEffect, useMemo, useState, type ReactNode } from "react"
import { Link, useNavigate, useParams } from "react-router-dom"
import {
  ArrowLeft,
  Check,
  Clock3,
  Gift,
  Layers3,
  PackageOpen,
  ShoppingCart,
  Sparkles,
  Timer,
  UserRound,
  Zap,
} from "lucide-react"
import { Button, Empty, Spin, message } from "antd"
import PublicSiteLayout, { PublicBanner } from "../components/PublicSiteLayout"
import RichTextContent from "../components/RichTextContent"
import { fetchPublicActivity, type ActivityProduct, type AdminActivity } from "../admin/api/activity"
import { claimActivityCoupon } from "../api/orders"
import { useAuth } from "../contexts/AuthContext"

function useClaimCoupon(activity: AdminActivity) {
  const navigate = useNavigate()
  const { user } = useAuth()
  const [claiming, setClaiming] = useState(false)

  const claim = async () => {
    const promoCodeId = activity.promo_code_id ?? activity.promo_code?.id
    if (!promoCodeId) {
      message.error("该活动未配置可领取的优惠券")
      return
    }
    if (!user) {
      message.info("请先登录后领取优惠券")
      navigate(`/login?redirect=${encodeURIComponent(`/activities/${activity.id}`)}`)
      return
    }
    setClaiming(true)
    try {
      await claimActivityCoupon(promoCodeId, activity.id)
      message.success("领取成功，正在前往购物车")
      navigate(`/cart?coupon_id=${promoCodeId}`)
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail ?? "领取失败，请稍后重试")
    } finally {
      setClaiming(false)
    }
  }

  return { claim, claiming }
}

const AUDIENCE_LABELS: Record<string, string> = { all: "全部用户", new_user: "新用户", member: "会员用户", agent: "代理用户" }
const MODE_LABELS: Record<string, string> = { direct: "直接参与", existing_discount: "商品折扣", promo_code: "优惠码参与", activity_price: "活动专享价" }
const CYCLE_LABELS: Record<string, string> = { hourly: "小时", daily: "天", monthly: "月", quarterly: "季", semi_annually: "半年", annually: "年", biennially: "两年", triennially: "三年", one_time: "一次性" }
const TEMPLATE_LABELS: Record<string, string> = { standard: "标准活动", product_grid: "商品矩阵", flash_sale: "限时抢购", coupon: "优惠码专题" }

interface ActivitySection {
  name: string
  description: string | null
  products: ActivityProduct[]
}

export default function ActivityDetail() {
  const { id } = useParams()
  const [activity, setActivity] = useState<AdminActivity | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const activityID = Number(id)
    if (!Number.isInteger(activityID) || activityID <= 0) { setLoading(false); return }
    let mounted = true
    setLoading(true)
    fetchPublicActivity(activityID)
      .then((data) => { if (mounted) setActivity(data ?? null) })
      .catch(() => { if (mounted) setActivity(null) })
      .finally(() => { if (mounted) setLoading(false) })
    return () => { mounted = false }
  }, [id])

  const sections = useMemo(() => groupProducts(activity?.products ?? []), [activity])

  if (loading) return <PublicSiteLayout><div className="activity-detail-state"><Spin size="large" /></div></PublicSiteLayout>
  if (!activity) return <PublicSiteLayout><div className="activity-detail-state"><Empty description="活动不存在或尚未发布"><Button type="primary" href="/activities">返回活动中心</Button></Empty></div></PublicSiteLayout>

  return (
    <PublicSiteLayout>
      <main className={`activity-detail-page template-${activity.template_key}`}>
        <PublicBanner title={activity.title} description={activity.subtitle || activity.description} background={activity.banner_url || activity.image_url || "/hero-new-user.jpeg"} />
        <ActivitySummary activity={activity} />
        <ActivityTemplate activity={activity} sections={sections} />
      </main>
    </PublicSiteLayout>
  )
}

function ActivitySummary({ activity }: { activity: AdminActivity }) {
  return (
    <section className="activity-detail-summary-band">
      <div className="www-public-container activity-detail-summary">
        <Link to="/activities" className="activity-back"><ArrowLeft />活动中心</Link>
        <div className="activity-summary-meta">
          <span><Clock3 />{activity.limited_time ? `${formatDate(activity.starts_at)} 至 ${formatDate(activity.ends_at)}` : "长期有效"}</span>
          <span><UserRound />{AUDIENCE_LABELS[activity.audience] || activity.audience}</span>
          <span><ShoppingCart />{MODE_LABELS[activity.participation_mode] || activity.participation_mode}</span>
          <span><Layers3 />{TEMPLATE_LABELS[activity.template_key] || "活动专题"}</span>
          <strong className={`activity-status is-${activity.status}`}>{activity.status_text}</strong>
        </div>
      </div>
    </section>
  )
}

function ActivityTemplate({ activity, sections }: { activity: AdminActivity; sections: ActivitySection[] }) {
  switch (activity.template_key) {
    case "product_grid":
      return <ProductGridTemplate activity={activity} sections={sections} />
    case "flash_sale":
      return <FlashSaleTemplate activity={activity} sections={sections} />
    case "coupon":
      return <CouponTemplate activity={activity} sections={sections} />
    default:
      return <StandardTemplate activity={activity} sections={sections} />
  }
}

function StandardTemplate({ activity, sections }: { activity: AdminActivity; sections: ActivitySection[] }) {
  return (
    <div className="activity-detail-main-band">
      <div className="www-public-container activity-detail-flow">
        <ActivityIntro activity={activity} eyebrow="ACTIVITY OVERVIEW" />
        <ProductSections activity={activity} sections={sections} variant="standard" />
        <ActivityRules activity={activity} />
      </div>
    </div>
  )
}

function ProductGridTemplate({ activity, sections }: { activity: AdminActivity; sections: ActivitySection[] }) {
  const count = sections.reduce((sum, section) => sum + section.products.length, 0)
  return (
    <div className="activity-detail-main-band">
      <div className="www-public-container activity-detail-flow">
        <ActivityIntro activity={activity} eyebrow="PRODUCT COLLECTION" compact />
        <div className="activity-grid-overview activity-template-enter">
          <div><Layers3 /><span>活动分区</span><strong>{sections.length}</strong></div>
          <div><PackageOpen /><span>参与产品</span><strong>{count}</strong></div>
          <div><Sparkles /><span>专属权益</span><strong>{MODE_LABELS[activity.participation_mode]}</strong></div>
        </div>
        <ProductSections activity={activity} sections={sections} variant="product_grid" />
        <ActivityRules activity={activity} />
      </div>
    </div>
  )
}

function FlashSaleTemplate({ activity, sections }: { activity: AdminActivity; sections: ActivitySection[] }) {
  return (
    <div className="activity-detail-main-band">
      <FlashCountdown activity={activity} />
      <div className="www-public-container activity-detail-flow">
        <ActivityIntro activity={activity} eyebrow="FLASH SALE" compact />
        <ProductSections activity={activity} sections={sections} variant="flash_sale" />
        <ActivityRules activity={activity} />
      </div>
    </div>
  )
}

function CouponTemplate({ activity, sections }: { activity: AdminActivity; sections: ActivitySection[] }) {
  return (
    <div className="activity-detail-main-band">
      <div className="www-public-container activity-detail-flow">
        <CouponClaim activity={activity} />
        <ActivityIntro activity={activity} eyebrow="COUPON BENEFITS" compact />
        <ProductSections activity={activity} sections={sections} variant="coupon" />
        <ActivityRules activity={activity} />
      </div>
    </div>
  )
}

function ActivityIntro({ activity, eyebrow, compact = false }: { activity: AdminActivity; eyebrow: string; compact?: boolean }) {
  return (
    <section className={`activity-intro-block activity-template-enter ${compact ? "is-compact" : ""}`}>
      <div className="activity-intro-heading">
        <p className="activity-eyebrow">{eyebrow}</p>
        <h2>{activity.subtitle || activity.title}</h2>
        <p className="activity-lead">{activity.description}</p>
      </div>
      {activity.content && <div className="activity-intro-content"><RichTextContent value={activity.content} /></div>}
      {!compact && activity.promo_code && <CouponInline activity={activity} />}
    </section>
  )
}

function CouponClaim({ activity }: { activity: AdminActivity }) {
  const code = activity.promo_code?.code
  const canClaim = Boolean(activity.promo_code_id ?? activity.promo_code?.id)
  const claimable = canClaim && activity.status === "ongoing"
  const { claim, claiming } = useClaimCoupon(activity)
  return (
    <section className="activity-coupon-claim activity-template-enter">
      <div className="activity-coupon-icon"><Gift /></div>
      <div className="activity-coupon-copy">
        <span>活动专享优惠</span>
        <h2>{code || "优惠权益已配置"}</h2>
        <p>{activity.promo_code?.description || "参与活动的商品将按后台配置的优惠规则结算。"}</p>
      </div>
      {canClaim ? (
        <Button type="primary" icon={<Gift />} loading={claiming} disabled={!claimable} onClick={() => void claim()}>
          {activity.status === "upcoming" ? "即将开始" : activity.status === "ended" ? "活动已结束" : "立即领取"}
        </Button>
      ) : (
        <span className="activity-coupon-mode">{MODE_LABELS[activity.participation_mode]}</span>
      )}
    </section>
  )
}

function CouponInline({ activity }: { activity: AdminActivity }) {
  const code = activity.promo_code?.code
  const canClaim = Boolean(activity.promo_code_id ?? activity.promo_code?.id)
  const claimable = canClaim && activity.status === "ongoing"
  const { claim, claiming } = useClaimCoupon(activity)
  if (!code && !canClaim) return null
  return (
    <div className="activity-coupon-inline">
      <div><span>活动优惠码</span><strong>{code || "专属优惠"}</strong></div>
      <Button type="primary" icon={<Gift />} loading={claiming} disabled={!claimable} onClick={() => void claim()}>
        {activity.status === "ongoing" ? "领取并使用" : activity.status === "upcoming" ? "即将开始" : "已结束"}
      </Button>
    </div>
  )
}

function FlashCountdown({ activity }: { activity: AdminActivity }) {
  const [now, setNow] = useState(() => Date.now())
  useEffect(() => {
    const timer = window.setInterval(() => setNow(Date.now()), 1000)
    return () => window.clearInterval(timer)
  }, [])
  const target = activity.status === "upcoming" ? activity.starts_at : activity.ends_at
  const parts = countdownParts(target, now)
  return (
    <section className="activity-flash-bar">
      <div className="www-public-container activity-flash-inner">
        <div><Zap /><span>{activity.status === "upcoming" ? "距离活动开始" : activity.status === "ended" ? "本场抢购已结束" : "距离活动结束"}</span></div>
        <div className="activity-countdown">
          <strong>{parts.days}</strong><span>天</span><strong>{parts.hours}</strong><span>时</span><strong>{parts.minutes}</strong><span>分</span><strong>{parts.seconds}</strong><span>秒</span>
        </div>
        <span className="activity-flash-limit">{activity.total_limit > 0 ? `限量 ${activity.total_limit} 份` : "限时特惠"}</span>
      </div>
    </section>
  )
}

function ProductSections({ activity, sections, variant }: { activity: AdminActivity; sections: ActivitySection[]; variant: "standard" | "product_grid" | "flash_sale" | "coupon" }) {
  if (sections.length === 0) return <ActivityNoProducts activity={activity} variant={variant} />
  return (
    <div className={`activity-sections variant-${variant}`}>
      {sections.map((section) => (
        <section key={section.name} className="activity-product-section">
          <header className="activity-section-heading activity-template-enter">
            <div><span>{variant === "flash_sale" ? <Timer /> : variant === "coupon" ? <Gift /> : <Layers3 />}</span><h2>{section.name}</h2></div>
            {section.description && <p>{section.description}</p>}
          </header>
          <div className="activity-product-grid">
            {section.products.map((product, index) => (
              <ActivityProductCard key={product.id ?? product.product_id} product={product} activity={activity} variant={variant} disabled={activity.status !== "ongoing"} delay={index * 60} />
            ))}
          </div>
        </section>
      ))}
    </div>
  )
}

function ActivityNoProducts({ activity, variant }: { activity: AdminActivity; variant: string }) {
  const copy: Record<string, { title: string; description: string; icon: ReactNode }> = {
    standard: { title: "活动权益现已开放", description: "本活动暂未绑定指定产品，可前往产品中心按活动规则参与。", icon: <Sparkles /> },
    product_grid: { title: "产品矩阵待发布", description: "后台尚未添加参与产品，添加后会自动按分区形成商品矩阵。", icon: <Layers3 /> },
    flash_sale: { title: "抢购商品准备中", description: "限时场次已经建立，参与商品与库存发布后将在这里展示。", icon: <Timer /> },
    coupon: { title: "优惠权益可用于指定产品", description: "后台添加参与产品后，会在这里展示可用商品和券后权益。", icon: <Gift /> },
  }
  const current = copy[variant] || copy.standard
  return (
    <section className={`activity-no-products is-${variant}`}>
      <span>{current.icon}</span>
      <div><h2>{current.title}</h2><p>{current.description}</p></div>
      <Link to={activity.target_url || "/store"}>{activity.button_text || "查看产品"}</Link>
    </section>
  )
}

function ActivityRules({ activity }: { activity: AdminActivity }) {
  if (!activity.rules) return null
  return (
    <section className="activity-rules-block activity-template-enter">
      <header><span>RULES</span><h2>活动规则</h2></header>
      <RichTextContent value={activity.rules} />
    </section>
  )
}

function ActivityProductCard({ product, activity, variant, disabled, delay }: { product: ActivityProduct; activity: AdminActivity; variant: string; disabled: boolean; delay: number }) {
  const price = product.activity_price ?? product.pricing?.price ?? 0
  const originalPrice = product.activity_price != null ? product.pricing?.price : product.pricing?.original_price
  const features = [product.vcpu ? `${product.vcpu} 核 CPU` : null, product.memory, product.disk, product.bandwidth].filter((value): value is string => Boolean(value))
  const href = buildProductPurchaseURL(product.store_url || "/store", activity)
  const inventory = product.stock_limit > 0 ? product.stock_limit : product.stock_policy === "tracked" ? product.stock ?? 0 : 0
  return (
    <article className={`activity-product-card activity-template-enter style-${product.card_style || "a"} card-${variant}`} style={{ animationDelay: `${delay}ms` }}>
      <div className="activity-product-head">
        <div>
          <div className="activity-product-title"><h3>{product.name}</h3>{product.custom_label && <span>{product.custom_label}</span>}</div>
          <p>{product.product_description || `${product.category_name || "云产品"} · ${product.group_name || product.sku || "精选配置"}`}</p>
        </div>
        {inventory > 0 && <span className="activity-stock">剩余 {inventory}</span>}
      </div>
      <div className="activity-product-specs">
        {features.length > 0 ? features.map((feature) => <span key={feature}><Check />{feature}</span>) : <span><Check />标准产品配置</span>}
      </div>
      {variant === "flash_sale" && inventory > 0 && <div className="activity-stock-progress"><span style={{ width: `${Math.max(12, Math.min(92, 100 - inventory))}%` }} /></div>}
      <div className="activity-product-footer">
        <div className="activity-price-block">
          {product.discount_percent != null && <span className="activity-discount">{formatDiscount(product.discount_percent)}</span>}
          <div><small>¥</small><strong>{formatMoney(price)}</strong><span>/{CYCLE_LABELS[product.billing_cycle || product.pricing?.cycle || ""] || "起"}</span></div>
          {originalPrice != null && originalPrice > price && <del>日常价 ¥{formatMoney(originalPrice)}</del>}
        </div>
        {disabled ? <button type="button" disabled>{activity.status === "upcoming" ? "即将开始" : "活动已结束"}</button> : <Link to={href}>{variant === "flash_sale" ? "立即抢购" : activity.button_text || "立即参与"}</Link>}
      </div>
      {product.per_user_limit > 0 && <p className="activity-product-limit">每位用户限购 {product.per_user_limit} 件</p>}
    </article>
  )
}

function groupProducts(products: ActivityProduct[]): ActivitySection[] {
  const grouped = new Map<string, { description: string | null; products: ActivityProduct[] }>()
  for (const product of products) {
    const name = product.section_name || "精选产品"
    const section = grouped.get(name) ?? { description: product.section_description ?? null, products: [] }
    section.products.push(product)
    grouped.set(name, section)
  }
  return Array.from(grouped, ([name, value]) => ({ name, ...value }))
}

function countdownParts(value: string | null, now: number) {
  const distance = value ? Math.max(0, new Date(value).getTime() - now) : 0
  return {
    days: String(Math.floor(distance / 86400000)).padStart(2, "0"),
    hours: String(Math.floor(distance / 3600000) % 24).padStart(2, "0"),
    minutes: String(Math.floor(distance / 60000) % 60).padStart(2, "0"),
    seconds: String(Math.floor(distance / 1000) % 60).padStart(2, "0"),
  }
}

function buildProductPurchaseURL(path: string, activity: AdminActivity) {
  if (activity.participation_mode !== "promo_code" || !activity.promo_code_id) return path
  const [urlWithoutHash, hash = ""] = path.split("#", 2)
  const separator = urlWithoutHash.includes("?") ? "&" : "?"
  return `${urlWithoutHash}${separator}coupon_id=${encodeURIComponent(String(activity.promo_code_id))}${hash ? `#${hash}` : ""}`
}

function formatDate(value: string | null) {
  return value ? new Date(value).toLocaleString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hour12: false }) : "-"
}

function formatMoney(value: number) {
  return Number(value || 0).toFixed(2).replace(/\.00$/, "")
}

function formatDiscount(value: number) {
  const discount = value > 10 ? value / 10 : value
  return `${Number(discount.toFixed(2))} 折`
}
