import { useUserContext } from '@/contexts/UserContext'
import { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import type { User } from '@/api/system/user/model'
import { loginByOpenId } from '@/api/layout'
import { TenantId } from '@/config/app'

/**
 * useUser - 兼容性 Hook
 * 优先使用 UserContext，在未包裹 UserProvider 时降级为本地状态
 */
export const useUser = () => {
  try {
    const ctx = useUserContext()
    return ctx
  } catch {
    // 未在 UserProvider 中，使用降级逻辑
    return useUserFallback()
  }
}

/** 降级方案：不依赖 Context 的本地用户状态 */
const useUserFallback = () => {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)

  const loadFromStorage = () => {
    const token = Taro.getStorageSync('access_token')
    const userData = Taro.getStorageSync('User')
    if (token && userData) {
      const parsed = typeof userData === 'string' ? JSON.parse(userData) : userData
      setUser(parsed as User)
      return true
    }
    return !!token
  }

  const loginUser = (token: string, userInfo: User) => {
    Taro.setStorageSync('access_token', token)
    Taro.setStorageSync('User', userInfo)
    setUser(userInfo)
  }

  const logoutUser = () => {
    Taro.removeStorageSync('access_token')
    Taro.removeStorageSync('User')
    setUser(null)
  }

  const refreshUser = async () => {
    // 降级方案不自动刷新
    return user
  }

  const syncFromStorage = (): boolean => {
    return loadFromStorage()
  }

  useEffect(() => {
    const init = async () => {
      const hasLocal = loadFromStorage()
      if (!hasLocal) {
        try {
          const data = await new Promise<any>((resolve, reject) => {
            Taro.login({
              success: (res) => loginByOpenId({ code: res.code, tenantId: TenantId }).then(resolve).catch(reject),
              fail: reject,
            })
          })
          if (data?.access_token && data?.user) {
            loginUser(data.access_token, data.user)
          }
        } catch { /* ignore */ }
      }
      setLoading(false)
    }
    init()
  }, [])

  return { user, isLoggedIn: !!user, loading, loginUser, logoutUser, refreshUser, syncFromStorage }
}
