import { useState, useEffect, useCallback } from 'react'
import { checkAndCacheVipStatus, getVipStatusFromCache } from '@/utils/vip'
import { useUser } from '@/hooks/useUser'

/**
 * useVipStatus - 判断当前用户是否为 VIP 会员
 *
 * 工作原理：
 * 1. 首先从 localStorage 缓存快速读取（即时返回）
 * 2. 异步调用后端接口验证并更新缓存
 *
 * 使用场景：
 * - 商品详情页价格展示
 * - 结算页价格计算
 * - 任何需要判断 VIP 身份的页面
 */
export const useVipStatus = () => {
  const { user, isLoggedIn } = useUser()
  const [isVip, setIsVip] = useState<boolean>(getVipStatusFromCache())
  const [loading, setLoading] = useState(false)

  const refresh = useCallback(async () => {
    if (!isLoggedIn) {
      setIsVip(false)
      return
    }
    setLoading(true)
    try {
      const userId = (user as any)?.userId || (user as any)?.id
      const result = await checkAndCacheVipStatus(userId)
      setIsVip(result)
    } catch {
      // 保持缓存值
    } finally {
      setLoading(false)
    }
  }, [isLoggedIn, user])

  useEffect(() => {
    if (isLoggedIn) {
      refresh()
    } else {
      setIsVip(false)
    }
  }, [isLoggedIn, refresh])

  return { isVip, loading, refresh }
}
