import { loadBackendAuthTokens, loadBackendBaseUrl } from '../../utils/backendAuth'
import { getEventPlay, type BackendEventPlayResult } from '../../utils/backendApi'
import { formatBackendPlayActionText, formatBackendPlayStatusText } from '../../utils/backendPlayCopy'
import { reportBackendClientLog } from '../../utils/backendClientLogs'

type EventPageData = {
  eventId: string
  loading: boolean
  titleText: string
  summaryText: string
  releaseText: string
  actionText: string
  statusText: string
  variantModeText: string
  variantSummaryText: string
  presentationText: string
  contentBundleText: string
}

function formatAssignmentMode(mode?: string | null): string {
  if (mode === 'manual') {
    return '手动选择'
  }
  if (mode === 'random') {
    return '随机分配'
  }
  if (mode === 'server-assigned') {
    return '后台指定'
  }
  return '默认单赛道'
}

function formatVariantSummary(result: BackendEventPlayResult): string {
  const variants = result.play.courseVariants || []
  if (!variants.length) {
    return '当前未声明额外赛道版本'
  }

  const selectable = variants.filter((item) => item.selectable !== false)
  const preview = variants.slice(0, 3).map((item) => item.routeCode || item.name).join(' / ')
  const suffix = variants.length > 3 ? ' / ...' : ''
  return `${variants.length} 条赛道，可选 ${selectable.length} 条：${preview}${suffix}`
}

function formatPresentationSummary(result: BackendEventPlayResult): string {
  const currentPresentation = result.currentPresentation
  if (!currentPresentation) {
    return '当前发布 release 未绑定展示版本，或当前尚未发布'
  }

  const presentationId = currentPresentation.presentationId || '--'
  const templateKey = currentPresentation.templateKey || '--'
  const version = currentPresentation.version || '--'
  return `${presentationId} / ${templateKey} / ${version}`
}

function formatContentBundleSummary(result: BackendEventPlayResult): string {
  const currentContentBundle = result.currentContentBundle
  if (!currentContentBundle) {
    return '当前发布 release 未绑定内容包版本，或当前尚未发布'
  }

  const bundleId = currentContentBundle.bundleId || '--'
  const bundleType = currentContentBundle.bundleType || '--'
  const version = currentContentBundle.version || '--'
  return `${bundleId} / ${bundleType} / ${version}`
}

function getAccessToken(): string | null {
  const app = getApp<IAppOption>()
  const tokens = app.globalData && app.globalData.backendAuthTokens
    ? app.globalData.backendAuthTokens
    : loadBackendAuthTokens()
  return tokens && tokens.accessToken ? tokens.accessToken : null
}

Page({
  data: {
    eventId: '',
    loading: false,
    titleText: '活动详情',
    summaryText: '未加载',
    releaseText: '--',
    actionText: '--',
    statusText: '待加载',
    variantModeText: '--',
    variantSummaryText: '--',
    presentationText: '--',
    contentBundleText: '--',
  } as EventPageData,

  onLoad(query: { eventId?: string }) {
    const eventId = query && query.eventId ? decodeURIComponent(query.eventId) : ''
    if (!eventId) {
      this.setData({
        statusText: '缺少 eventId',
      })
      return
    }
    this.setData({ eventId })
    this.loadEventPlay(eventId)
  },

  async loadEventPlay(eventId?: string) {
    const targetEventId = eventId || this.data.eventId
    const accessToken = getAccessToken()
    if (!accessToken) {
      wx.redirectTo({ url: '/pages/login/login' })
      return
    }

    this.setData({
      loading: true,
      statusText: '正在加载活动上下文',
    })

    try {
      const result = await getEventPlay({
        baseUrl: loadBackendBaseUrl(),
        eventId: targetEventId,
        accessToken,
      })
      this.applyEventPlay(result)
    } catch (error) {
      const message = error && (error as { message?: string }).message ? (error as { message: string }).message : '未知错误'
      this.setData({
        loading: false,
        statusText: `活动加载失败：${message}`,
      })
    }
  },

  applyEventPlay(result: BackendEventPlayResult) {
    const assignmentMode = result.play.assignmentMode ? result.play.assignmentMode : null
    reportBackendClientLog({
      level: 'info',
      category: 'event-play',
      message: 'event play loaded',
      eventId: result.event.id || this.data.eventId || '',
      releaseId: result.resolvedRelease && result.resolvedRelease.releaseId
        ? result.resolvedRelease.releaseId
        : '',
      manifestUrl: result.resolvedRelease && result.resolvedRelease.manifestUrl
        ? result.resolvedRelease.manifestUrl
        : '',
      details: {
        pageEventId: this.data.eventId || '',
        resultEventId: result.event.id || '',
        primaryAction: result.play.primaryAction || '',
        detailStatus: result.play.reason || '',
        detailCanLaunch: result.play.canLaunch,
        detailCurrentPresentation: result.currentPresentation
          ? `${result.currentPresentation.presentationId || '--'} / ${result.currentPresentation.templateKey || '--'} / ${result.currentPresentation.version || '--'}`
          : '',
        detailCurrentContentBundle: result.currentContentBundle
          ? `${result.currentContentBundle.bundleId || '--'} / ${result.currentContentBundle.bundleType || '--'} / ${result.currentContentBundle.version || '--'}`
          : '',
        assignmentMode,
        variantCount: result.play.courseVariants ? result.play.courseVariants.length : 0,
      },
    })
    this.setData({
      loading: false,
      titleText: result.event.displayName,
      summaryText: result.event.summary || '暂无活动简介',
      releaseText: result.resolvedRelease
        ? `${result.resolvedRelease.configLabel} / ${result.resolvedRelease.releaseId}`
        : '当前无可用 release',
      actionText: formatBackendPlayActionText(result.play.primaryAction, result.play.reason),
      statusText: formatBackendPlayStatusText(result.play.canLaunch, result.play.primaryAction, result.play.reason),
      variantModeText: formatAssignmentMode(result.play.assignmentMode),
      variantSummaryText: formatVariantSummary(result),
      presentationText: formatPresentationSummary(result),
      contentBundleText: formatContentBundleSummary(result),
    })
  },

  handleRefresh() {
    this.loadEventPlay()
  },

  async handleLaunch() {
    wx.navigateTo({
      url: `/pages/event-prepare/event-prepare?eventId=${encodeURIComponent(this.data.eventId)}`,
    })
  },
})
