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 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 routerToCreate = () => {
    // 检查是否登录，如果未登录则跳转到登录页面
    if (!isLogin) {
      const redirectUrl = `/create/type`;
      router.push(`/login?redirect=${encodeURIComponent(redirectUrl)}`);
      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/type');
  }

  return {
    routerToCreate,
  };
}
 
export default useCreatorNavigation;