import { NavigateOptions } from "next/dist/shared/lib/app-router-context.shared-runtime";
import { usePathname, useRouter } from "next/navigation";
import { useCallback } from "react";

import { useLoadingStore } from "../stores/loadingStore";

const useCustomRouter = () => {
  //
  const { setLoading } = useLoadingStore();
  const { push, replace, refresh } = useRouter();
  const pathname = usePathname();

  const customPush = useCallback(
    (link: string, options?: NavigateOptions | undefined) => {
      if (pathname != link && !link.startsWith("http")) {
        setLoading(true);

        setTimeout(() => {
          setLoading(false);
        }, 5000);
      }
      push(link, options);
    },
    [push, pathname, setLoading],
  );

  const customReplace = useCallback(
    (link: string, options?: NavigateOptions | undefined) => {
      if (pathname != link && !link.startsWith("http")) {
        setLoading(true);

        setTimeout(() => {
          setLoading(false);
        }, 5000);
      }
      replace(link, options);
    },
    [replace, pathname, setLoading],
  );

  const customRouter = {
    push: customPush,
    replace: customReplace,
    refresh,
    pathname,
  };

  return customRouter;
};

export default useCustomRouter;
