<template>
  <section class="space-y-6">

    <div v-if="!hasAuth" class="mos-card border-dashed p-4 text-sm text-mosquito-ink/70">
      <div class="flex items-start gap-3">
        <div class="flex h-10 w-10 items-center justify-center rounded-2xl bg-mosquito-accent/10 text-mosquito-accent">!</div>
        <div>
          <div class="font-semibold text-mosquito-ink">未配置鉴权信息</div>
          <div class="mos-muted mt-1 text-xs">请设置 API Key 与用户令牌后查看活动列表。</div>
        </div>
      </div>
    </div>

    <div v-if="loadError" class="mos-card border-dashed p-4 text-sm text-rose-600">
      {{ loadError }}
    </div>

    <ListSection :page="page" :total-pages="totalPages" @prev="page--" @next="page++">
      <template #title>活动运营看板</template>
      <template #subtitle>查看活动列表并管理分享推广设置。</template>
      <template #filters>
        <input class="mos-input !py-1 !px-2 !text-xs w-48" v-model="query" placeholder="搜索活动名称" />
        <select class="mos-input !py-1 !px-2 !text-xs" v-model="statusFilter">
          <option value="">全部状态</option>
          <option value="进行中">进行中</option>
          <option value="未开始">未开始</option>
          <option value="已结束">已结束</option>
          <option value="待配置">待配置</option>
        </select>
        <input class="mos-input !py-1 !px-2 !text-xs" type="date" v-model="startDate" />
        <input class="mos-input !py-1 !px-2 !text-xs" type="date" v-model="endDate" />
      </template>
      <template #actions>
        <RouterLink to="/activities/new" class="rounded-xl bg-mosquito-accent px-3 py-2 text-sm font-semibold text-white shadow-soft">
          新建活动
        </RouterLink>
      </template>
      <template #default>
        <div v-if="pagedActivities.length" class="space-y-3">
          <RouterLink
            v-for="item in pagedActivities"
            :key="item.name"
            :to="`/activities/${item.id}`"
            class="flex items-center justify-between rounded-xl border border-mosquito-line px-4 py-3 transition hover:bg-mosquito-bg/60"
          >
            <div>
              <div class="text-sm font-semibold text-mosquito-ink">{{ item.name }}</div>
              <div class="mos-muted text-xs">{{ item.period }}</div>
            </div>
            <div class="flex items-center gap-4 text-xs text-mosquito-ink/70">
              <span>{{ item.participants }} 人参与</span>
              <span class="rounded-full bg-mosquito-accent/10 px-2 py-1 text-[10px] font-semibold text-mosquito-brand">{{ item.status }}</span>
            </div>
          </RouterLink>
        </div>
      </template>
      <template #empty>
        <div v-if="!pagedActivities.length" class="mt-6 rounded-xl border border-dashed border-mosquito-line p-6 text-sm text-mosquito-ink/70">
          <div class="flex items-start gap-3">
            <div class="flex h-10 w-10 items-center justify-center rounded-2xl bg-mosquito-accent/10 text-mosquito-accent">+</div>
            <div>
              <div class="font-semibold text-mosquito-ink">暂无活动数据</div>
              <div class="mos-muted mt-1 text-xs">点击“新建活动”开始配置分享任务。</div>
            </div>
          </div>
        </div>
      </template>
    </ListSection>

    <div class="mos-card p-5">
      <div class="flex items-center justify-between">
        <div>
          <div class="text-xs font-semibold text-mosquito-ink/70">排行榜预览</div>
          <div class="mos-muted mt-1 text-xs">数据来自 /api/v1/activities/{id}/leaderboard</div>
        </div>
        <span class="mos-pill">示例</span>
      </div>

      <div v-if="hasAuth && activitiesWithMeta.length" class="mt-4">
        <MosquitoLeaderboard
          :activity-id="activeActivityId"
          :top-n="3"
          :current-user-id="currentUserId"
        />
      </div>

      <div v-else-if="hasAuth" class="mt-6 rounded-xl border border-dashed border-mosquito-line p-6 text-sm text-mosquito-ink/70">
        <div class="flex items-start gap-3">
          <div class="flex h-10 w-10 items-center justify-center rounded-2xl bg-mosquito-accent/10 text-mosquito-accent">!</div>
          <div>
            <div class="font-semibold text-mosquito-ink">暂无活动榜单</div>
            <div class="mos-muted mt-1 text-xs">请先创建活动后再查看排行。</div>
          </div>
        </div>
      </div>

      <div v-else class="mt-6 rounded-xl border border-dashed border-mosquito-line p-6 text-sm text-mosquito-ink/70">
        <div class="flex items-start gap-3">
          <div class="flex h-10 w-10 items-center justify-center rounded-2xl bg-mosquito-accent/10 text-mosquito-accent">!</div>
          <div>
            <div class="font-semibold text-mosquito-ink">配置鉴权后可查看榜单</div>
            <div class="mos-muted mt-1 text-xs">请设置 API Key 与用户令牌。</div>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, RouterLink } from 'vue-router'
import MosquitoLeaderboard from '../../../components/MosquitoLeaderboard.vue'
import { getUserIdFromToken, parseUserId } from '../../../shared/auth'
import { useDataService } from '../services'
import ListSection from '../components/ListSection.vue'

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

const activityId = 1
const service = useDataService()
const route = useRoute()
const userToken = import.meta.env.VITE_MOSQUITO_USER_TOKEN
const hasAuth = computed(() => true)
const routeUserId = computed(() => parseUserId(route.query.userId ?? route.params.userId))
const currentUserId = computed(() => getUserIdFromToken(userToken) ?? routeUserId.value ?? undefined)
const activities = ref<ActivitySummary[]>([])
const loadError = ref('')
const activeActivityId = computed(() => activities.value[0]?.id ?? activityId)
const query = ref('')
const statusFilter = ref('')
const startDate = ref('')
const endDate = ref('')
const page = ref(0)
const pageSize = 6

const formatPeriod = (activity: ActivitySummary) => {
  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) => {
  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 activitiesWithMeta = computed(() =>
  activities.value.map((item) => ({
    id: item.id,
    name: item.name ?? `活动 #${item.id}`,
    period: formatPeriod(item),
    participants: 0,
    status: resolveStatus(item),
    startTime: item.startTime ?? '',
    endTime: item.endTime ?? ''
  }))
)

const filteredActivities = computed(() => {
  return activitiesWithMeta.value.filter((item) => {
    const matchesQuery = item.name.includes(query.value.trim())
    const matchesStatus = statusFilter.value ? item.status === statusFilter.value : true
    const startOk = startDate.value ? new Date(item.startTime).getTime() >= new Date(startDate.value).getTime() : true
    const endOk = endDate.value ? new Date(item.endTime).getTime() <= new Date(endDate.value).getTime() : true
    return matchesQuery && matchesStatus && startOk && endOk
  })
})

const totalPages = computed(() => Math.max(1, Math.ceil(filteredActivities.value.length / pageSize)))

const pagedActivities = computed(() => {
  const start = page.value * pageSize
  return filteredActivities.value.slice(start, start + pageSize)
})

watch([query, statusFilter, startDate, endDate], () => {
  page.value = 0
})

const loadActivities = async () => {
  loadError.value = ''
  try {
    const list = await service.getActivities()
    activities.value = list
  } catch (error) {
    loadError.value = '活动列表加载失败。'
  }
}

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