<template>
  <section class="mx-auto max-w-md px-4 pb-28 pt-6 space-y-6">
    <!-- Hero Section -->
    <header class="mos-hero relative overflow-hidden p-6">
      <div class="relative z-10">
        <div class="flex items-center gap-2">
          <span class="mos-pill mos-pill-accent">
            <Icons name="sparkles" class="w-3 h-3" />
            {{ activityStatus }}
          </span>
          <span class="text-xs text-white/70">{{ activityName }}</span>
        </div>
        
        <h1 class="mos-title mt-4 text-2xl font-bold text-white">{{ heroTitle }}</h1>
        <p class="mt-2 text-sm text-white/80">
          {{ heroSubtitle }}
        </p>
        
        <div class="mt-6 flex flex-wrap gap-3">
          <RouterLink to="/share" class="mos-btn mos-btn-primary">
            <Icons name="rocket" class="w-4 h-4" />
            立即分享
          </RouterLink>
          <a href="#rules" class="mos-btn mos-btn-ghost !border-white/30 !text-white hover:!bg-white/10">
            <Icons name="target" class="w-4 h-4" />
            查看规则
          </a>
        </div>
        
        <div class="mt-4 text-xs text-white/60 flex items-center gap-1">
          <Icons name="crown" class="w-3 h-3" />
          {{ activityPeriod }}
        </div>
      </div>
    </header>

    <!-- KPI Cards -->
    <section class="grid grid-cols-2 gap-4">
      <div class="mos-kpi-card">
        <div class="mos-kpi-icon mos-kpi-icon-primary">
          <Icons name="trending-up" class="w-5 h-5" />
        </div>
        <div class="text-xs font-semibold text-mosquito-muted">本周访问</div>
        <div class="mos-kpi mt-1 text-2xl">{{ formatNumber(kpis.visits) }}</div>
        <div class="text-xs text-mosquito-muted mt-1">{{ kpiHints.visits }}</div>
      </div>
      
      <div class="mos-kpi-card">
        <div class="mos-kpi-icon mos-kpi-icon-secondary">
          <Icons name="share" class="w-5 h-5" />
        </div>
        <div class="text-xs font-semibold text-mosquito-muted">分享次数</div>
        <div class="mos-kpi mt-1 text-2xl">{{ formatNumber(kpis.shares) }}</div>
        <div class="text-xs text-mosquito-muted mt-1">{{ kpiHints.shares }}</div>
      </div>
      
      <div class="mos-kpi-card">
        <div class="mos-kpi-icon mos-kpi-icon-accent">
          <Icons name="users" class="w-5 h-5" />
        </div>
        <div class="text-xs font-semibold text-mosquito-muted">转化人数</div>
        <div class="mos-kpi mt-1 text-2xl">{{ formatNumber(kpis.conversions) }}</div>
        <div class="text-xs text-mosquito-muted mt-1">{{ kpiHints.conversions }}</div>
      </div>
      
      <div class="mos-kpi-card">
        <div class="mos-kpi-icon mos-kpi-icon-primary">
          <Icons name="gift" class="w-5 h-5" />
        </div>
        <div class="text-xs font-semibold text-mosquito-muted">我的奖励</div>
        <div class="mos-kpi mt-1 text-2xl">{{ formatNumber(kpis.rewards) }}</div>
        <div class="text-xs text-mosquito-muted mt-1">{{ kpiHints.rewards }}</div>
      </div>
    </section>

    <!-- Rules Section -->
    <section id="rules" class="mos-card space-y-4 p-5">
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-2">
          <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-mosquito-primary to-mosquito-primary-light flex items-center justify-center text-white">
            <Icons name="target" class="w-5 h-5" />
          </div>
          <div>
            <h2 class="mos-title text-lg font-bold">活动规则</h2>
            <p class="text-xs text-mosquito-muted">完成关键步骤解锁奖励</p>
          </div>
        </div>
        <span class="mos-pill mos-pill-primary">5 条规则</span>
      </div>
      
      <ol class="space-y-3">
        <li v-for="(rule, index) in rules" :key="index" class="flex gap-3 p-3 rounded-xl bg-mosquito-bg/50">
          <span class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-mosquito-primary text-white text-sm font-bold">
            {{ index + 1 }}
          </span>
          <span class="text-sm text-mosquito-ink-light leading-relaxed">{{ rule }}</span>
        </li>
      </ol>
    </section>

    <!-- Leaderboard Preview -->
    <section class="space-y-4">
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-2">
          <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-mosquito-accent to-mosquito-accent-light flex items-center justify-center text-mosquito-ink">
            <Icons name="crown" class="w-5 h-5" />
          </div>
          <div>
            <h2 class="mos-title text-lg font-bold">排行榜</h2>
            <p class="text-xs text-mosquito-muted">实时排名，持续更新</p>
          </div>
        </div>
        <RouterLink to="/rank" class="mos-btn mos-btn-secondary !py-2 !px-4 !text-sm">
          完整榜单
          <Icons name="arrow-right" class="w-4 h-4" />
        </RouterLink>
      </div>

      <div v-if="hasAuth && activeActivityId" class="mos-card p-4">
        <MosquitoLeaderboard :activity-id="activeActivityId" :top-n="3" :size="6" :current-user-id="userId" />
      </div>

      <div v-else class="mos-card border-dashed p-6 text-center">
        <div class="mos-empty-icon">
          <Icons name="trophy" class="w-8 h-8" />
        </div>
        <h3 class="font-semibold text-mosquito-ink">暂无榜单数据</h3>
        <p class="text-sm text-mosquito-muted mt-1">参与活动后可查看实时排名</p>
      </div>
    </section>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import MosquitoLeaderboard from '../../../components/MosquitoLeaderboard.vue'
import { MosquitoError, useMosquito } from '../../../index'
import { getUserIdFromToken, parseUserId } from '../../../shared/auth'
import Icons from '../components/Icons.vue'

type ActivitySummary = {
  id: number
  name: string
  startTime?: string
  endTime?: string
}

const route = useRoute()
const apiKey = import.meta.env.VITE_MOSQUITO_API_KEY
const userToken = import.meta.env.VITE_MOSQUITO_USER_TOKEN
const routeUserId = computed(() => parseUserId(route.query.userId ?? route.params.userId))
const userId = computed(() => getUserIdFromToken(userToken) ?? routeUserId.value ?? 0)
const hasAuth = computed(() => Boolean(apiKey && userToken && userId.value))
const { getActivities, getActivityStats, getShareMetrics, getRewards } = useMosquito()

const activities = ref<ActivitySummary[]>([])
const activeActivity = computed(() => activities.value[0] ?? null)
const activeActivityId = computed(() => activeActivity.value?.id ?? 0)

const kpis = ref({
  visits: null as number | null,
  shares: null as number | null,
  conversions: null as number | null,
  rewards: null as number | null
})

const kpiHints = ref({
  visits: '等待首批数据',
  shares: '绑定 API 后自动更新',
  conversions: '活动开启后可见',
  rewards: '分享成功后累计'
})

const rules = [
  '分享专属链接给好友，好友点击即计入访问',
  '好友完成注册后计入转化，累计积分自动增加',
  '每日 24 点结算排名，前 10 名获得额外奖励',
  '同一好友仅计入一次转化，防止重复计数',
  '奖励将在活动结束后 7 日内发放'
]

const activityName = computed(() => activeActivity.value?.name ?? '裂变增长计划')
const activityStatus = computed(() => resolveStatus(activeActivity.value))
const heroTitle = computed(() => (activeActivity.value ? '邀请好友，解锁双倍奖励' : '当前暂无活动'))
const heroSubtitle = computed(() =>
  activeActivity.value
    ? '完成分享任务即可累计积分，前 10 名将额外获得加码奖励'
    : '请先创建活动后再开启分享推广'
)
const activityPeriod = computed(() => formatPeriod(activeActivity.value))

const formatNumber = (value: number | null) => {
  if (value === null || Number.isNaN(value)) {
    return '--'
  }
  return value.toLocaleString('zh-CN')
}

const formatPeriod = (activity: ActivitySummary | null) => {
  if (!activity?.startTime || !activity?.endTime) {
    return '活动时间待配置'
  }
  const start = new Date(activity.startTime)
  const end = new Date(activity.endTime)
  if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
    return '活动时间待配置'
  }
  return `${start.toLocaleDateString('zh-CN')} - ${end.toLocaleDateString('zh-CN')}`
}

const resolveStatus = (activity: ActivitySummary | null) => {
  if (!activity?.startTime || !activity?.endTime) {
    return '活动未配置'
  }
  const now = Date.now()
  const start = new Date(activity.startTime).getTime()
  const end = new Date(activity.endTime).getTime()
  if (Number.isNaN(start) || Number.isNaN(end)) {
    return '活动未配置'
  }
  if (now < start) {
    return '即将开始'
  }
  if (now > end) {
    return '活动已结束'
  }
  return '活动进行中'
}

const loadData = async () => {
  if (!hasAuth.value) {
    return
  }
  try {
    const list = await getActivities()
    activities.value = list
    const activity = activeActivity.value
    if (!activity) {
      return
    }
    const activityId = activity.id

    const [stats, metrics, rewards] = await Promise.all([
      getActivityStats(activityId),
      getShareMetrics(activityId),
      getRewards(activityId, userId.value)
    ])

    kpis.value.visits = metrics?.totalClicks ?? 0
    kpis.value.shares = stats?.totalShares ?? 0
    kpis.value.conversions = stats?.totalParticipants ?? 0
    kpis.value.rewards = Array.isArray(rewards)
      ? rewards.reduce((sum, item) => sum + (item.points || 0), 0)
      : 0
    kpiHints.value = {
      visits: '7 天内访问次数',
      shares: '累计分享次数',
      conversions: '累计转化人数',
      rewards: '累计奖励积分'
    }
  } catch (error) {
    if (error instanceof MosquitoError && error.statusCode === 401) {
      kpiHints.value = {
        visits: '未授权访问',
        shares: '未授权访问',
        conversions: '未授权访问',
        rewards: '未授权访问'
      }
      return
    }
    kpiHints.value = {
      visits: '数据加载失败',
      shares: '数据加载失败',
      conversions: '数据加载失败',
      rewards: '数据加载失败'
    }
  }
}

onMounted(() => {
  loadData()
})
</script>