<template>
  <section class="space-y-6">
    <header class="flex flex-wrap items-center justify-between gap-4">
      <div>
        <h1 class="mos-title text-2xl font-semibold">运营概览</h1>
        <p class="mos-muted mt-2 text-sm">监控关键指标与活动状态，快速定位异常。</p>
      </div>
      <div class="flex items-center gap-2 text-xs text-mosquito-ink/60">
        <span class="rounded-full bg-mosquito-accent/10 px-3 py-1 font-semibold text-mosquito-brand">Production</span>
        最近更新：{{ updatedAt }}
      </div>
    </header>

    <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>

    <section class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
      <div v-for="card in kpis" :key="card.label" class="mos-card p-5">
        <div class="flex items-center justify-between">
          <div class="text-xs font-semibold text-mosquito-ink/70">{{ card.label }}</div>
          <span class="rounded-full bg-mosquito-accent/10 px-2 py-1 text-[10px] font-semibold text-mosquito-brand">
            {{ card.status }}
          </span>
        </div>
        <div class="mos-kpi mt-4 text-2xl font-semibold text-mosquito-ink">{{ formatNumber(card.value) }}</div>
        <div class="mos-muted mt-2 text-xs">{{ card.hint }}</div>
      </div>
    </section>

    <section class="grid gap-6 lg:grid-cols-3">
      <div class="mos-card lg:col-span-2 p-5">
        <div class="flex items-center justify-between">
          <div>
            <h2 class="mos-title text-lg font-semibold">活动列表</h2>
            <p class="mos-muted mt-1 text-xs">跟踪当前活动的进展与参与度。</p>
          </div>
          <RouterLink to="/activities" class="text-sm font-semibold text-mosquito-accent">查看全部</RouterLink>
        </div>

        <div v-if="activitiesWithMeta.length" class="mt-4 space-y-3">
          <RouterLink
            v-for="item in activitiesWithMeta"
            :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>

        <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">创建第一个活动，开始追踪分享转化。</div>
            </div>
          </div>
        </div>
      </div>

      <div class="mos-card p-5">
        <h2 class="mos-title text-lg font-semibold">异常/告警</h2>
        <p class="mos-muted mt-1 text-xs">监控回调失败与鉴权异常。</p>

        <div v-if="alerts.length" class="mt-4 space-y-3">
          <div v-for="alert in alerts" :key="alert.title" class="rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
            <div class="font-semibold">{{ alert.title }}</div>
            <div class="text-xs text-rose-600">{{ alert.detail }}</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">系统运行正常，保持监控即可。</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { RouterLink } from 'vue-router'
import { useDataService } from '../services'

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

const service = useDataService()
const hasAuth = computed(() => true)

const updatedAt = ref('刚刚')
const loadError = ref('')
const activities = ref<ActivitySummary[]>([])
const alerts: { title: string; detail: string }[] = []
const kpis = ref([
  { label: '访问', value: null as number | null, status: '待同步', hint: '接入埋点后显示实时数据' },
  { label: '分享', value: null as number | null, status: '待同步', hint: '活动开启后统计分享次数' },
  { label: '转化', value: null as number | null, status: '待同步', hint: '用户注册转化将在此展示' },
  { label: '新增', value: null as number | null, status: '待同步', hint: '当前暂无新增用户' }
])

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

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 loadData = async () => {
  loadError.value = ''
  try {
    const data = await service.getDashboard()
    updatedAt.value = data.updatedAt
    kpis.value = data.kpis
    activities.value = data.activities
    alerts.splice(0, alerts.length, ...data.alerts)
  } catch (error) {
    loadError.value = '数据加载失败，请稍后重试。'
  }
}

const activitiesWithMeta = computed(() =>
  activities.value.map((item) => ({
    id: item.id,
    name: item.name,
    period: formatPeriod(item),
    participants: 0,
    status: resolveStatus(item)
  }))
)

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