import { loadBackendAuthTokens, loadBackendBaseUrl } from '../../utils/backendAuth'
import { getMyResults, type BackendSessionResultView } from '../../utils/backendApi'

type ResultsPageData = {
  loading: boolean
  statusText: string
  results: Array<{
    sessionId: string
    titleText: string
    statusText: string
    scoreText: string
    routeText: string
    runtimeText: string
  }>
}

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 formatRouteSummary(result: BackendSessionResultView): string {
  const session = result.session
  if (session.variantName && session.routeCode) {
    return `${session.variantName} / ${session.routeCode}`
  }
  if (session.variantName) {
    return session.variantName
  }
  if (session.routeCode) {
    return session.routeCode
  }
  return '默认赛道'
}

function formatRuntimeSummary(result: BackendSessionResultView): string {
  const runtime = result.session.runtime
  if (!runtime) {
    return '运行对象 --'
  }

  const placeText = runtime.placeName || runtime.placeId || '--'
  const mapText = runtime.mapName || runtime.mapId || '--'
  const variantText = runtime.courseVariantId || result.session.variantName || result.session.variantId || '--'
  return `地点 ${placeText} / 地图 ${mapText} / 赛道 ${variantText}`
}

function buildResultCardView(result: BackendSessionResultView) {
  return {
    sessionId: result.session.id,
    titleText: result.session.eventName || result.session.id,
    statusText: `${result.result.status} / ${result.session.status}`,
    scoreText: `得分 ${result.result.finalScore || '--'} / 用时 ${result.result.finalDurationSec || '--'}s`,
    routeText: `赛道 ${formatRouteSummary(result)}`,
    runtimeText: formatRuntimeSummary(result),
  }
}

Page({
  data: {
    loading: false,
    statusText: '准备加载历史结果',
    results: [],
  } as ResultsPageData,

  onLoad() {
    this.loadResults()
  },

  onShow() {
    this.loadResults()
  },

  async loadResults() {
    const accessToken = getAccessToken()
    if (!accessToken) {
      wx.redirectTo({ url: '/pages/login/login' })
      return
    }

    this.setData({
      loading: true,
      statusText: '正在加载历史结果',
    })

    try {
      const results = await getMyResults({
        baseUrl: loadBackendBaseUrl(),
        accessToken,
        limit: 20,
      })
      this.setData({
        loading: false,
        statusText: `历史结果加载完成，共 ${results.length} 条`,
        results: results.map(buildResultCardView),
      })
    } catch (error) {
      const message = error && (error as { message?: string }).message ? (error as { message: string }).message : '未知错误'
      this.setData({
        loading: false,
        statusText: `历史结果加载失败：${message}`,
      })
    }
  },

  handleOpenResult(event: WechatMiniprogram.TouchEvent) {
    const sessionId = event.currentTarget.dataset.sessionId as string | undefined
    if (!sessionId) {
      return
    }
    wx.navigateTo({
      url: `/pages/result/result?sessionId=${encodeURIComponent(sessionId)}`,
    })
  },
})
