import { useMemo } from 'react';
import { router, usePage } from '@inertiajs/react';

/**
 * Inertia-backed replacements for the `next/navigation` hooks used by the original Next.js sources.
 */

function currentUrl(url: string): URL {
  const origin =
    typeof window !== 'undefined' ? window.location.origin : 'http://localhost';
  return new URL(url, origin);
}

/** Current pathname, e.g. `/account/billing/basic`. */
export function usePathname(): string {
  const { url } = usePage();
  return useMemo(() => currentUrl(url).pathname, [url]);
}

/** Current query string as URLSearchParams. */
export function useSearchParams(): URLSearchParams {
  const { url } = usePage();
  return useMemo(() => currentUrl(url).searchParams, [url]);
}

export interface AppRouter {
  push: (href: string) => void;
  replace: (href: string) => void;
  back: () => void;
  forward: () => void;
  refresh: () => void;
  prefetch: (href: string) => void;
}

export function useRouter(): AppRouter {
  return useMemo(
    () => ({
      push: (href: string) => router.visit(href),
      replace: (href: string) => router.visit(href, { replace: true }),
      back: () => window.history.back(),
      forward: () => window.history.forward(),
      refresh: () => router.reload(),
      prefetch: (href: string) => router.prefetch(href),
    }),
    [],
  );
}

/** Client-side redirect (Next's `redirect()` equivalent). */
export function redirect(href: string): never {
  router.visit(href, { replace: true });
  throw new Error(`Redirecting to ${href}`);
}
