import Taro from '@tarojs/taro'
import { getUserInfo, getWxOpenId } from '@/api/layout'
import {
  checkAndHandleInviteRelation,
  getStoredInviteParams,
  hasPendingInvite,
  parseInviteParams,
  saveInviteParams,
  trackInviteSource,
} from '@/utils/invite'

const TABBAR_URLS = ['/pages/index/index', '/pages/order/order', '/pages/user/user']

export function decodeRedirect(input?: string): string {
  if (!input) return ''
  try {
    const decoded = decodeURIComponent(input)
    return decoded.startsWith('/') ? decoded : `/${decoded}`
  } catch {
    return input.startsWith('/') ? input : `/${input}`
  }
}

export function getRedirectUrl(): string {
  const router = Taro.getCurrentInstance().router
  return decodeRedirect((router?.params as Record<string, string> | undefined)?.redirect)
}

export function hideLoginTabBar() {
  // passport 页面不是 tabBar 页面，无需调用 hideTabBar
}

export function persistInviteFromRoute(sourceFallback = 'share') {
  try {
    const router = Taro.getCurrentInstance().router
    const inviteParams = parseInviteParams({ query: router?.params })
    if (inviteParams?.inviter) {
      saveInviteParams(inviteParams)
      trackInviteSource(inviteParams.source || sourceFallback, parseInt(inviteParams.inviter, 10))
    }
  } catch {
  }
}

export function getInviteRefereeId(): number {
  const inviteParams = getStoredInviteParams()
  return inviteParams?.inviter ? parseInt(inviteParams.inviter, 10) : 0
}

export function buildAuthUrl(path: string, redirectUrl?: string): string {
  const inviteParams = getStoredInviteParams()
  const params: Record<string, string> = {}

  if (redirectUrl) params.redirect = redirectUrl
  if (inviteParams?.inviter) params.inviter = inviteParams.inviter
  if (inviteParams?.source) params.source = inviteParams.source
  if (inviteParams?.t) params.t = inviteParams.t

  const query = Object.entries(params)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&')

  return `${path}${query ? `?${query}` : ''}`
}

export async function getWeappLoginCode(): Promise<string | undefined> {
  try {
    const res = await new Promise<{ code?: string }>((resolve, reject) => {
      Taro.login({ success: (r) => resolve(r), fail: reject })
    })
    return res?.code
  } catch {
    return undefined
  }
}

export async function ensureWxOpenIdSaved(wxLoginCode?: string) {
  const code = wxLoginCode || (await getWeappLoginCode())
  if (!code) return

  await getWxOpenId({ code })

  try {
    const freshUser = await getUserInfo()
    if (freshUser) {
      Taro.setStorageSync('User', freshUser)
    }
  } catch {
  }
}

export async function handlePostLogin(redirectUrl?: string) {
  if (hasPendingInvite()) {
    try {
      await checkAndHandleInviteRelation()
    } catch {
    }
  }

  const target = redirectUrl || '/pages/index/index'
  if (TABBAR_URLS.includes(target.split('?')[0])) {
    await Taro.switchTab({ url: target.split('?')[0] })
    return
  }

  if (target === '/pages/index/index') {
    await Taro.reLaunch({ url: target })
    return
  }

  await Taro.redirectTo({ url: target })
}
