import { clearBackendAuthTokens, saveBackendAuthTokens, saveBackendBaseUrl } from '../../utils/backendAuth'
import { loginWechatMini } from '../../utils/backendApi'
import { setGlobalMockDebugBridgeEnabled } from '../../utils/globalMockDebugBridge'

const DEFAULT_BACKEND_BASE_URL = 'https://api.gotomars.xyz'
const DEFAULT_DEVICE_KEY = 'mini-dev-device-001'
const DEFAULT_DEV_CODE = 'dev-workbench-user'

type LoginPageData = {
  backendBaseUrl: string
  deviceKey: string
  loginCode: string
  statusText: string
}

function setAppBackendState(baseUrl: string, accessToken: string, refreshToken: string) {
  const app = getApp<IAppOption>()
  if (app.globalData) {
    app.globalData.backendBaseUrl = baseUrl
    app.globalData.backendAuthTokens = { accessToken, refreshToken }
  }
}

Page({
  data: {
    backendBaseUrl: DEFAULT_BACKEND_BASE_URL,
    deviceKey: DEFAULT_DEVICE_KEY,
    loginCode: DEFAULT_DEV_CODE,
    statusText: '请先登录后端',
  } as LoginPageData,

  onLoad() {
    const app = getApp<IAppOption>()
    this.setData({
      backendBaseUrl: app.globalData && app.globalData.backendBaseUrl
        ? app.globalData.backendBaseUrl
        : DEFAULT_BACKEND_BASE_URL,
    })
  },
  handleBaseUrlInput(event: WechatMiniprogram.Input) {
    this.setData({ backendBaseUrl: event.detail.value })
  },

  handleDeviceKeyInput(event: WechatMiniprogram.Input) {
    this.setData({ deviceKey: event.detail.value })
  },

  handleLoginCodeInput(event: WechatMiniprogram.Input) {
    this.setData({ loginCode: event.detail.value })
  },

  persistBaseUrl(): string {
    const normalized = saveBackendBaseUrl(this.data.backendBaseUrl)
    const app = getApp<IAppOption>()
    if (app.globalData) {
      app.globalData.backendBaseUrl = normalized
    }
    if (normalized !== this.data.backendBaseUrl) {
      this.setData({ backendBaseUrl: normalized })
    }
    return normalized
  },

  async loginWithCode(code: string, sourceLabel: string) {
    const baseUrl = this.persistBaseUrl()
    this.setData({
      statusText: `正在用 ${sourceLabel} 登录后端`,
    })
    try {
      const result = await loginWechatMini({
        baseUrl,
        code,
        deviceKey: this.data.deviceKey || DEFAULT_DEVICE_KEY,
        clientType: 'wechat',
      })
      const tokens = saveBackendAuthTokens(result.tokens)
      setAppBackendState(baseUrl, tokens.accessToken, tokens.refreshToken)
      this.setData({
        statusText: '登录成功，准备进入首页',
      })
      wx.redirectTo({
        url: '/pages/home/home',
      })
    } catch (error) {
      const message = error && (error as { message?: string }).message ? (error as { message: string }).message : '未知错误'
      this.setData({
        statusText: `登录失败：${message}`,
      })
    }
  },

  handleLoginWithDevCode() {
    this.loginWithCode((this.data.loginCode || DEFAULT_DEV_CODE).trim(), '开发码')
  },

  handleLoginWithWechat() {
    this.setData({
      statusText: '正在调用 wx.login',
    })
    wx.login({
      success: (result) => {
        const code = result && result.code ? result.code : ''
        if (!code) {
          this.setData({ statusText: 'wx.login 未返回 code' })
          return
        }
        this.setData({ loginCode: code })
        this.loginWithCode(code, 'wx.login code')
      },
      fail: (error) => {
        this.setData({
          statusText: `wx.login 失败：${error && error.errMsg ? error.errMsg : '未知错误'}`,
        })
      },
    })
  },

  handleClearLoginState() {
    clearBackendAuthTokens()
    setGlobalMockDebugBridgeEnabled(false)
    const app = getApp<IAppOption>()
    if (app.globalData) {
      app.globalData.backendAuthTokens = null
    }
    this.setData({
      statusText: '已清空登录态',
    })
  },
})
