import { useEffect, useState } from "react"
import { Link } from "react-router-dom"
import { ArrowRight, CalendarDays } from "lucide-react"
import { Alert, Button, Empty, Spin } from "antd"
import PublicSiteLayout, { PublicBanner } from "../components/PublicSiteLayout"
import { fetchPublicActivities, type ActivityStatus, type AdminActivity } from "../admin/api/activity"
import { isCommercialError } from "../api/client"

const TABS: { key: "all" | Exclude<ActivityStatus, "draft">; label: string }[] = [
  { key: "all", label: "全部活动" },
  { key: "ongoing", label: "正在进行" },
  { key: "upcoming", label: "活动预告" },
  { key: "ended", label: "已结束" },
]

const STATUS_CLASS: Record<string, string> = {
  ongoing: "is-ongoing",
  upcoming: "is-upcoming",
  ended: "is-ended",
}

export default function Activities() {
  const [active, setActive] = useState<(typeof TABS)[number]["key"]>("all")
  const [items, setItems] = useState<AdminActivity[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState("")
  const [reloadKey, setReloadKey] = useState(0)

  useEffect(() => {
    let mounted = true
    setLoading(true)
    setError("")
    fetchPublicActivities(active)
      .then((data) => { if (mounted) setItems(data) })
      .catch((requestError) => {
        if (!mounted) return
        setItems([])
        if (isCommercialError(requestError)) return
        const detail = requestError?.response?.data?.detail
        setError(typeof detail === "string" ? detail : "活动数据加载失败，请稍后重试。")
      })
      .finally(() => { if (mounted) setLoading(false) })
    return () => { mounted = false }
  }, [active, reloadKey])

  return (
    <PublicSiteLayout>
      <main className="activity-public-page">
        <PublicBanner
          title="最新活动"
          description="汇集云产品限时特惠、新用户权益与长期优惠，选择适合当前业务的上云方案。"
          background="/hero-new-user.jpeg"
        />

        <section className="activity-tabs-band">
          <div className="www-public-container">
            <nav className="activity-tabs" aria-label="活动状态">
              {TABS.map((tab) => (
                <button key={tab.key} type="button" className={active === tab.key ? "is-active" : ""} onClick={() => setActive(tab.key)}>
                  {tab.label}
                </button>
              ))}
            </nav>
          </div>
        </section>

        <section className="activity-list-section">
          <div className="www-public-container">
            {loading ? (
              <div className="activity-loading"><Spin size="large" /></div>
            ) : error ? (
              <div className="activity-empty"><Alert type="error" showIcon message="无法加载活动" description={error} action={<Button onClick={() => setReloadKey((value) => value + 1)}>重新加载</Button>} /></div>
            ) : items.length === 0 ? (
              <div className="activity-empty">
                <Empty description="暂无相关活动" />
                <p className="activity-more-tip">更多优惠活动，敬请期待！</p>
              </div>
            ) : (
              <div className="activity-list-grid">
                {items.map((activity, index) => (
                  <Link
                    key={activity.id}
                    to={`/activities/${activity.id}`}
                    className="activity-list-card"
                    style={{ animationDelay: `${(index % 3) * 80}ms` }}
                  >
                    <div className="activity-list-cover">
                      <img src={activity.image_url || activity.banner_url || "/hero-new-user.jpeg"} alt={activity.title} />
                    </div>
                    <div className="activity-list-body">
                      <div className="activity-list-tags">
                        <span className={`activity-status-badge ${STATUS_CLASS[activity.status] || ""}`}>{activity.status_text}</span>
                        {activity.label && <span className="activity-ribbon">{activity.label}</span>}
                      </div>
                      <div className="activity-list-text">
                        <h2>{activity.title}</h2>
                        <p>{activity.description}</p>
                      </div>
                      <div className="activity-list-meta">
                        <span className="activity-list-time"><CalendarDays aria-hidden="true" />{activity.limited_time ? `${formatDate(activity.starts_at)} 至 ${formatDate(activity.ends_at)}` : "长期有效"}</span>
                        <span className="activity-list-link">查看活动 <ArrowRight aria-hidden="true" /></span>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            )}
          </div>
        </section>
      </main>
    </PublicSiteLayout>
  )
}

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