import { clearBackendAuthTokens, loadBackendAuthTokens, loadBackendBaseUrl } from '../../utils/backendAuth'
import { getEntryHome, type BackendCardResult, type BackendEntryHomeResult } from '../../utils/backendApi'

const DEFAULT_CHANNEL_CODE = 'mini-demo'
const DEFAULT_CHANNEL_TYPE = 'wechat_mini'

type HomePageData = {
  loading: boolean
  statusText: string
  userNameText: string
  tenantText: string
  channelText: string
  ongoingSessionText: string
  recentSessionText: string
  ongoingRuntimeText: string
  recentRuntimeText: string
  cards: BackendCardResult[]
}

function formatSessionSummary(session?: BackendEntryHomeResult['ongoingSession'] | null): string {
  if (!session) {
    return '无'
  }

  const title = session.eventName || session.eventDisplayName || session.eventId || session.id || session.sessionId
  const status = session.status || session.sessionStatus || '--'
  const route = session.routeCode || session.variantName || '默认赛道'
  return `${title} / ${status} / ${route}`
}

function formatRuntimeSummary(session?: BackendEntryHomeResult['ongoingSession'] | null): string {
  if (!session || !session.runtime) {
    return '运行对象 --'
  }

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

function requireAuthToken(): 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: {
    loading: false,
    statusText: '准备加载首页',
    userNameText: '--',
    tenantText: '--',
    channelText: '--',
    ongoingSessionText: '无',
    recentSessionText: '无',
    ongoingRuntimeText: '运行对象 --',
    recentRuntimeText: '运行对象 --',
    cards: [],
  } as HomePageData,

  onLoad() {
    this.loadEntryHome()
  },

  onShow() {
    this.loadEntryHome()
  },

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

    this.setData({
      loading: true,
      statusText: '正在加载首页聚合',
    })

    try {
      const result = await getEntryHome({
        baseUrl: loadBackendBaseUrl(),
        accessToken,
        channelCode: DEFAULT_CHANNEL_CODE,
        channelType: DEFAULT_CHANNEL_TYPE,
      })
      this.applyEntryHomeResult(result)
    } catch (error) {
      const message = error && (error as { message?: string }).message ? (error as { message: string }).message : '未知错误'
      this.setData({
        loading: false,
        statusText: `首页加载失败：${message}`,
      })
    }
  },

  applyEntryHomeResult(result: BackendEntryHomeResult) {
    this.setData({
      loading: false,
      statusText: '首页加载完成',
      userNameText: result.user.nickname || result.user.publicId || result.user.id,
      tenantText: `${result.tenant.name} (${result.tenant.code})`,
      channelText: `${result.channel.displayName} / ${result.channel.code}`,
      ongoingSessionText: formatSessionSummary(result.ongoingSession),
      recentSessionText: formatSessionSummary(result.recentSession),
      ongoingRuntimeText: formatRuntimeSummary(result.ongoingSession),
      recentRuntimeText: formatRuntimeSummary(result.recentSession),
      cards: result.cards || [],
    })
  },

  handleRefresh() {
    this.loadEntryHome()
  },

  handleOpenCard(event: WechatMiniprogram.TouchEvent) {
    const eventId = event.currentTarget.dataset.eventId as string | undefined
    if (!eventId) {
      wx.showToast({
        title: '该卡片暂无活动入口',
        icon: 'none',
      })
      return
    }

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

  handleOpenRecentResult() {
    wx.navigateTo({
      url: '/pages/results/results',
    })
  },

  handleLogout() {
    clearBackendAuthTokens()
    const app = getApp<IAppOption>()
    if (app.globalData) {
      app.globalData.backendAuthTokens = null
    }
    wx.redirectTo({
      url: '/pages/login/login',
    })
  },
})
