import { loadBackendAuthTokens, loadBackendBaseUrl } from '../../utils/backendAuth'
import {
  getExperienceMapDetail,
  getPublicExperienceMapDetail,
  type BackendContentBundleSummary,
  type BackendDefaultExperienceSummary,
  type BackendExperienceMapDetail,
  type BackendPresentationSummary,
} from '../../utils/backendApi'
import { reportBackendClientLog } from '../../utils/backendClientLogs'

type DefaultExperienceCardView = {
  eventId: string
  titleText: string
  subtitleText: string
  statusText: string
  ctaText: string
  eventTypeText: string
  presentationText: string
  contentBundleText: string
  disabled: boolean
}

type ExperienceMapPageData = {
  mapId: string
  loading: boolean
  statusText: string
  placeText: string
  mapText: string
  summaryText: string
  tileInfoText: string
  cards: DefaultExperienceCardView[]
}

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
}

function formatPresentationSummary(summary?: BackendPresentationSummary | null): string {
  if (!summary) {
    return '当前未声明展示版本'
  }
  return summary.version || summary.templateKey || summary.presentationId || '当前未声明展示版本'
}

function formatContentBundleSummary(summary?: BackendContentBundleSummary | null): string {
  if (!summary) {
    return '当前未声明内容包版本'
  }
  return summary.version || summary.bundleType || summary.bundleId || '当前未声明内容包版本'
}

function buildDefaultExperienceCard(item: BackendDefaultExperienceSummary): DefaultExperienceCardView {
  const eventId = item.eventId || ''
  return {
    eventId,
    titleText: item.title || '未命名体验活动',
    subtitleText: item.subtitle || '当前暂无副标题',
    statusText: item.status || item.statusCode || '状态待确认',
    ctaText: item.ctaText || '查看体验',
    eventTypeText: item.eventType || '类型待确认',
    presentationText: formatPresentationSummary(item.currentPresentation),
    contentBundleText: formatContentBundleSummary(item.currentContentBundle),
    disabled: !eventId,
  }
}

Page({
  data: {
    mapId: '',
    loading: false,
    statusText: '准备加载地图详情',
    placeText: '地点待确认',
    mapText: '地图待确认',
    summaryText: '当前暂无地图摘要',
    tileInfoText: '瓦片信息待确认',
    cards: [],
  } as ExperienceMapPageData,

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

  onShow() {
    if (this.data.mapId) {
      this.loadMapDetail(this.data.mapId)
    }
  },

  async loadMapDetail(mapId?: string) {
    const targetMapId = mapId || this.data.mapId
    const accessToken = getAccessToken()

    this.setData({
      loading: true,
      statusText: '正在加载地图详情',
    })

    try {
      const baseUrl = loadBackendBaseUrl()
      const result = accessToken
        ? await getExperienceMapDetail({
          baseUrl,
          accessToken,
          mapAssetId: targetMapId,
        })
        : await getPublicExperienceMapDetail({
          baseUrl,
          mapAssetId: targetMapId,
        })
      this.applyDetail(result)
    } catch (error) {
      const message = error && (error as { message?: string }).message ? (error as { message: string }).message : '未知错误'
      this.setData({
        loading: false,
        statusText: `地图详情加载失败：${message}`,
        cards: [],
      })
    }
  },

  applyDetail(result: BackendExperienceMapDetail) {
    const cards = (result.defaultExperiences || []).map(buildDefaultExperienceCard)
    reportBackendClientLog({
      level: 'info',
      category: 'experience-map-detail',
      message: 'experience map detail loaded',
      details: {
        guestMode: !getAccessToken(),
        mapId: result.mapId || this.data.mapId || '',
        placeId: result.placeId || '',
        defaultExperienceCount: cards.length,
        defaultExperienceEventIds: (result.defaultExperiences || []).map((item) => item.eventId || ''),
      },
    })

    const tileBase = result.tileBaseUrl || ''
    const tileMeta = result.tileMetaUrl || ''
    const tileInfoText = tileBase || tileMeta
      ? `底图 ${tileBase || '--'} / Meta ${tileMeta || '--'}`
      : '当前未声明瓦片信息'

    this.setData({
      loading: false,
      statusText: cards.length ? '地图详情加载完成' : '当前地图暂无默认体验活动',
      placeText: result.placeName || result.placeId || '地点待确认',
      mapText: result.mapName || result.mapId || '地图待确认',
      summaryText: result.summary || '当前暂无地图摘要',
      tileInfoText,
      cards,
    })
  },

  handleRefresh() {
    this.loadMapDetail()
  },

  handleOpenExperience(event: WechatMiniprogram.TouchEvent) {
    const eventId = event.currentTarget.dataset.eventId as string | undefined
    reportBackendClientLog({
      level: 'info',
      category: 'experience-map-detail',
      message: 'default experience clicked',
      eventId: eventId || '',
      details: {
        mapId: this.data.mapId || '',
        clickedEventId: eventId || '',
      },
    })

    if (!eventId) {
      wx.showToast({
        title: '该体验活动暂无入口',
        icon: 'none',
      })
      return
    }

    wx.navigateTo({
      url: `/pages/event/event?eventId=${encodeURIComponent(eventId)}`,
    })
  },
})
