"use client";

import type { AnchorHTMLAttributes, PropsWithChildren, ReactNode } from "react";
import { createContext, forwardRef, useContext } from "react";
import NextLink from "next/link";
import { useParams as useNextParams, usePathname } from "next/navigation";

type LinkBaseProps = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "className"> & {
  className?: string;
  prefetch?: boolean;
  reloadDocument?: boolean;
  replace?: boolean;
  scroll?: boolean;
  state?: unknown;
  to: string;
};

export type LinkProps = LinkBaseProps;

export type NavLinkProps = Omit<LinkBaseProps, "className"> & {
  caseSensitive?: boolean;
  className?: string | ((props: { isActive: boolean; isPending: boolean }) => string | undefined);
  end?: boolean;
};

type LocationLike = {
  hash: string;
  key: string;
  pathname: string;
  search: string;
  state: null;
};

const OutletContext = createContext<ReactNode>(null);

const isExternalHref = (href: string) => /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href);

const normalizePath = (href: string) => {
  const [path] = href.split(/[?#]/);
  return path || "/";
};

export const BrowserRouter = ({ children }: PropsWithChildren) => <>{children}</>;

export const Routes = ({ children }: PropsWithChildren) => <>{children}</>;

type RouteProps = PropsWithChildren<{
  element?: ReactNode;
  index?: boolean;
  path?: string;
}>;

export const Route = ({ children, element }: RouteProps) => <>{element ?? children ?? null}</>;

export const Outlet = () => <>{useContext(OutletContext)}</>;

export const OutletProvider = ({
  children,
  outlet,
}: PropsWithChildren<{ outlet: ReactNode }>) => (
  <OutletContext.Provider value={outlet}>{children}</OutletContext.Provider>
);

export const Link = forwardRef<HTMLAnchorElement, LinkProps>(
  ({ prefetch, reloadDocument, replace, scroll, to, ...props }, ref) => {
    if (reloadDocument || isExternalHref(to)) {
      return <a ref={ref} href={to} {...props} />;
    }

    return (
      <NextLink
        ref={ref}
        href={to}
        prefetch={prefetch}
        replace={replace}
        scroll={scroll}
        {...props}
      />
    );
  },
);

Link.displayName = "Link";

export const NavLink = forwardRef<HTMLAnchorElement, NavLinkProps>(
  ({ caseSensitive, className, end, to, ...props }, ref) => {
    const pathname = usePathname() || "/";
    const target = normalizePath(to);
    const current = caseSensitive ? pathname : pathname.toLowerCase();
    const normalizedTarget = caseSensitive ? target : target.toLowerCase();
    const isActive = end
      ? current === normalizedTarget
      : current === normalizedTarget || current.startsWith(`${normalizedTarget}/`);

    return (
      <Link
        ref={ref}
        to={to}
        className={typeof className === "function" ? className({ isActive, isPending: false }) : className}
        {...props}
      />
    );
  },
);

NavLink.displayName = "NavLink";

export const useLocation = (): LocationLike => {
  const pathname = usePathname() || "/";

  return {
    hash: "",
    key: pathname,
    pathname,
    search: "",
    state: null,
  };
};

export const useParams = <T extends Record<string, string | string[] | undefined>>() =>
  useNextParams() as T;
