import { loadBackendAuthTokens, loadBackendBaseUrl } from '../../utils/backendAuth'
import { getExperienceMaps, getPublicExperienceMaps, type BackendExperienceMapSummary } from '../../utils/backendApi'
import { reportBackendClientLog } from '../../utils/backendClientLogs'

type ExperienceMapCardView = {
  mapId: string
  placeText: string
  mapText: string
  summaryText: string
  coverUrl: string
  defaultExperienceText: string
  disabled: boolean
}

type ExperienceMapsPageData = {
  loading: boolean
  statusText: string
  cards: ExperienceMapCardView[]
}

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 buildCardView(item: BackendExperienceMapSummary): ExperienceMapCardView {
  const mapId = item.mapId || ''
  const defaultExperienceCount = typeof item.defaultExperienceCount === 'number' ? item.defaultExperienceCount : 0
  return {
    mapId,
    placeText: item.placeName || item.placeId || '地点待确认',
    mapText: item.mapName || item.mapId || '地图待确认',
    summaryText: item.summary || '当前暂无地图摘要',
    coverUrl: item.coverUrl || '',
    defaultExperienceText: defaultExperienceCount > 0 ? `默认体验 ${defaultExperienceCount} 个` : '当前暂无默认体验活动',
    disabled: !mapId,
  }
}

Page({
  data: {
    loading: false,
    statusText: '准备加载地图体验列表',
    cards: [],
  } as ExperienceMapsPageData,

  onLoad() {
    this.loadMaps()
  },

  onShow() {
    this.loadMaps()
  },

  async loadMaps() {
    const accessToken = getAccessToken()

    this.setData({
      loading: true,
      statusText: '正在加载地图体验列表',
    })

    try {
      const baseUrl = loadBackendBaseUrl()
      const result = accessToken
        ? await getExperienceMaps({
          baseUrl,
          accessToken,
        })
        : await getPublicExperienceMaps({
          baseUrl,
        })
      reportBackendClientLog({
        level: 'info',
        category: 'experience-maps',
        message: 'experience maps loaded',
        details: {
          guestMode: !accessToken,
          mapCount: result.length,
          mapIds: result.map((item) => item.mapId || ''),
          mapsWithDefaultExperience: result.filter((item) => {
            return typeof item.defaultExperienceCount === 'number' && item.defaultExperienceCount > 0
          }).length,
        },
      })
      const cards = result.map(buildCardView)
      this.setData({
        loading: false,
        statusText: cards.length ? '地图体验列表加载完成' : '当前没有可体验地图',
        cards,
      })
    } catch (error) {
      const message = error && (error as { message?: string }).message ? (error as { message: string }).message : '未知错误'
      this.setData({
        loading: false,
        statusText: `地图体验列表加载失败：${message}`,
        cards: [],
      })
    }
  },

  handleRefresh() {
    this.loadMaps()
  },

  handleOpenMap(event: WechatMiniprogram.TouchEvent) {
    const mapId = event.currentTarget.dataset.mapId as string | undefined
    reportBackendClientLog({
      level: 'info',
      category: 'experience-maps',
      message: 'experience map clicked',
      details: {
        clickedMapId: mapId || '',
      },
    })
    if (!mapId) {
      wx.showToast({
        title: '该地图暂无详情入口',
        icon: 'none',
      })
      return
    }

    wx.navigateTo({
      url: `/pages/experience-map/experience-map?mapId=${encodeURIComponent(mapId)}`,
    })
  },
})
