<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">{{ activity?.name || '活动详情' }}</h1>
        <p class="mos-muted mt-2 text-sm">{{ activity?.description }}</p>
      </div>
      <div class="flex items-center gap-2">
        <span class="mos-pill">{{ statusLabel }}</span>
        <button class="mos-btn mos-btn-secondary" @click="toggleStatus">
          {{ toggleLabel }}
        </button>
        <button class="mos-btn mos-btn-accent" @click="endActivity">下线</button>
      </div>
    </header>

    <div class="grid gap-4 md:grid-cols-4">
      <div class="mos-card p-4" v-for="metric in metricsCards" :key="metric.label">
        <div class="text-xs font-semibold text-mosquito-ink/70">{{ metric.label }}</div>
        <div class="mos-kpi mt-3 text-xl font-semibold">{{ metric.value }}</div>
        <div class="mos-muted mt-1 text-xs">{{ metric.hint }}</div>
      </div>
    </div>

    <div class="grid gap-6 lg:grid-cols-3">
      <div class="mos-card lg:col-span-2 p-5 space-y-4">
        <div class="text-sm font-semibold text-mosquito-ink">活动配置</div>
        <div class="grid gap-4 md:grid-cols-2 text-sm">
          <div>
            <div class="text-xs text-mosquito-ink/70">目标人群</div>
            <div class="font-semibold">{{ activity?.config.audience }}</div>
          </div>
          <div>
            <div class="text-xs text-mosquito-ink/70">转化条件</div>
            <div class="font-semibold">{{ activity?.config.conversion }}</div>
          </div>
          <div>
            <div class="text-xs text-mosquito-ink/70">奖励规则</div>
            <div class="font-semibold">{{ activity?.config.reward }}</div>
          </div>
          <div>
            <div class="text-xs text-mosquito-ink/70">预算/限额</div>
            <div class="font-semibold">{{ activity?.config.budget }}</div>
          </div>
        </div>
        <RouterLink to="/activities/config" class="text-sm font-semibold text-mosquito-accent">
          进入配置向导
        </RouterLink>
      </div>

      <div class="mos-card p-5 space-y-4">
        <div class="flex items-center justify-between">
          <div class="text-sm font-semibold text-mosquito-ink">导出</div>
          <select class="mos-input !py-1 !px-2 !text-xs" v-model="exportType">
            <option value="summary">活动摘要</option>
            <option value="conversions">转化明细</option>
            <option value="rewards">奖励明细</option>
          </select>
        </div>
        <ExportFieldPanel
          :title="exportTitle"
          :fields="currentFields"
          :selected="currentSelected"
          @update:selected="setCurrentSelected"
          @export="exportData"
        />
      </div>
    </div>

    <div class="mos-card p-5 space-y-4">
      <div class="text-sm font-semibold text-mosquito-ink">排行榜预览</div>
      <MosquitoLeaderboard v-if="activity" :activity-id="activity.id" :top-n="5" />
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, RouterLink } from 'vue-router'
import MosquitoLeaderboard from '../../../components/MosquitoLeaderboard.vue'
import { useActivityStore } from '../stores/activities'
import { useAuditStore } from '../stores/audit'
import type { ActivityItem } from '../stores/activities'
import { downloadCsv } from '../utils/export'
import ExportFieldPanel, { type ExportField } from '../components/ExportFieldPanel.vue'
import { useExportFields } from '../composables/useExportFields'

const route = useRoute()
const store = useActivityStore()
const auditStore = useAuditStore()
const activity = ref<ActivityItem | null>(null)

const loadActivity = () => {
  const id = Number(route.params.id)
  activity.value = store.byId(id)
}

const statusLabel = computed(() => {
  if (!activity.value) return '未知'
  const map: Record<string, string> = {
    draft: '草稿',
    scheduled: '待上线',
    active: '进行中',
    paused: '已暂停',
    ended: '已结束'
  }
  return map[activity.value.status] ?? '未知'
})

const toggleLabel = computed(() => {
  if (!activity.value) return '切换状态'
  return activity.value.status === 'active' ? '暂停' : '上线'
})

const toggleStatus = () => {
  if (!activity.value) return
  const next = activity.value.status === 'active' ? 'paused' : 'active'
  activity.value = store.updateStatus(activity.value.id, next)
  auditStore.addLog(next === 'active' ? '上线活动' : '暂停活动', activity.value?.name ?? '活动')
}

const endActivity = () => {
  if (!activity.value) return
  activity.value = store.updateStatus(activity.value.id, 'ended')
  auditStore.addLog('下线活动', activity.value?.name ?? '活动')
}

const metricsCards = computed(() => {
  if (!activity.value) return []
  return [
    { label: '访问', value: activity.value.metrics.visits, hint: '近 7 天访问次数' },
    { label: '分享', value: activity.value.metrics.shares, hint: '累计分享次数' },
    { label: '转化', value: activity.value.metrics.conversions, hint: '累计转化人数' },
    { label: '预算消耗', value: activity.value.metrics.budgetUsed, hint: '已消耗积分' }
  ]
})

type ExportType = 'summary' | 'conversions' | 'rewards'

const exportType = ref<ExportType>('summary')
const summaryFields: ExportField[] = [
  { key: 'name', label: '活动名称', required: true },
  { key: 'status', label: '状态' },
  { key: 'startTime', label: '开始时间' },
  { key: 'endTime', label: '结束时间' },
  { key: 'visits', label: '访问' },
  { key: 'shares', label: '分享' },
  { key: 'conversions', label: '转化' },
  { key: 'budgetUsed', label: '预算消耗' }
]
const conversionFields: ExportField[] = [
  { key: 'user', label: '用户', required: true },
  { key: 'channel', label: '来源' },
  { key: 'convertedAt', label: '转化时间' },
  { key: 'reward', label: '奖励' }
]
const rewardFields: ExportField[] = [
  { key: 'user', label: '用户', required: true },
  { key: 'points', label: '积分' },
  { key: 'status', label: '状态' },
  { key: 'issuedAt', label: '发放时间' }
]

const exportFieldsMap: Record<ExportType, ExportField[]> = {
  summary: summaryFields,
  conversions: conversionFields,
  rewards: rewardFields
}

const exportStates = {
  summary: useExportFields(summaryFields, summaryFields.map((field) => field.key)),
  conversions: useExportFields(conversionFields, conversionFields.map((field) => field.key)),
  rewards: useExportFields(rewardFields, rewardFields.map((field) => field.key))
}

const exportTitle = computed(() => {
  if (exportType.value === 'summary') return '导出活动摘要字段'
  if (exportType.value === 'conversions') return '导出转化明细字段'
  return '导出奖励明细字段'
})

const currentFields = computed(() => exportFieldsMap[exportType.value])
const currentSelected = computed(() => exportStates[exportType.value].selected.value)

const setCurrentSelected = (next: string[]) => {
  exportStates[exportType.value].setSelected(next)
}

const exportData = () => {
  const fields = currentFields.value
  const selectedKeys = currentSelected.value
  const filename = `${activity.value?.name ?? 'activity'}-${exportType.value}.csv`

  if (exportType.value === 'summary') {
    const values: Record<string, string> = {
      name: activity.value?.name ?? '',
      status: statusLabel.value,
      startTime: activity.value?.startTime ?? '',
      endTime: activity.value?.endTime ?? '',
      visits: String(activity.value?.metrics.visits ?? 0),
      shares: String(activity.value?.metrics.shares ?? 0),
      conversions: String(activity.value?.metrics.conversions ?? 0),
      budgetUsed: String(activity.value?.metrics.budgetUsed ?? 0)
    }
    const rows = fields
      .filter((field) => selectedKeys.includes(field.key))
      .map((field) => [field.label, values[field.key] ?? ''])
    downloadCsv(filename, ['字段', '值'], rows)
    return
  }

  const sample = exportType.value === 'conversions'
    ? {
        user: '示例用户',
        channel: '分享链接',
        convertedAt: new Date().toLocaleString('zh-CN'),
        reward: '20 积分'
      }
    : {
        user: '示例用户',
        points: '20',
        status: '已发放',
        issuedAt: new Date().toLocaleString('zh-CN')
      }

  const rows = fields
    .filter((field) => selectedKeys.includes(field.key))
    .map((field) => [field.label, String(sample[field.key as keyof typeof sample] ?? '')])
  downloadCsv(filename, ['字段', '值'], rows)
}

onMounted(loadActivity)
</script>
