import { useEffect } from 'react'
import { usePathname, useRouter } from 'next/navigation'
import { useCurrentUser, useToken } from './auth'
import { useSetAtom } from 'jotai'
import { isCreateAiLimitReachedDialogOpenAtom } from '@/atoms/global'
import { VipType } from '@/services/wallet'
import { isVipDrawerOpenAtom } from '@/atoms/im'

const CREATE_CHARACTER_ROUTE = '/create/type'

const useCreatorNavigation = () => {
  const router = useRouter()
  const pathname = usePathname()
  const { data: currentUser } = useCurrentUser()
  const { isLogin } = useToken()
  const { isMember, canCreateAiCount, createdAiCount } = currentUser || {}
  const setIsCreateAiLimitReachedDialogOpen = useSetAtom(isCreateAiLimitReachedDialogOpenAtom)
  const setIsVipDrawerOpen = useSetAtom(isVipDrawerOpenAtom)

  const loginRedirectHref = `/login?redirect=${encodeURIComponent(CREATE_CHARACTER_ROUTE)}`

  useEffect(() => {
    // 根据登录状态选择性 prefetch，避免缓存重定向响应
    if (isLogin) {
      router.prefetch(CREATE_CHARACTER_ROUTE)
    } else {
      router.prefetch(loginRedirectHref)
    }
  }, [router, loginRedirectHref, isLogin])

  const routerToCreate = () => {
    // 检查是否登录，如果未登录则跳转到登录页面
    if (!isLogin) {
      router.push(loginRedirectHref)
      return
    }

    if ((createdAiCount ?? 0) >= (canCreateAiCount ?? 0)) {
      if (isMember) {
        setIsCreateAiLimitReachedDialogOpen(true)
        return
      } else {
        setIsVipDrawerOpen({ open: true, vipType: VipType.ADD_CREATE_AI })
        return
      }
    }

    localStorage.setItem('before_creator_navigation', pathname)
    router.push(CREATE_CHARACTER_ROUTE)
  }

  return {
    routerToCreate,
  }
}

export default useCreatorNavigation
