import { NavLink as RouterNavLink, NavLinkProps, useNavigate } from "react-router-dom";
import { forwardRef } from "react";
import { cn } from "@/lib/utils";

interface NavLinkCompatProps extends Omit<NavLinkProps, "className"> {
  className?: string;
  activeClassName?: string;
  pendingClassName?: string;
}

const NavLink = forwardRef<HTMLAnchorElement, NavLinkCompatProps>(
  ({ className, activeClassName, pendingClassName, to, onClick, ...props }, ref) => {
    const navigate = useNavigate();

    const isExternalTo = (value: NavLinkProps["to"]): boolean => {
      if (typeof value !== "string") return false;
      return /^(https?:)?\/\//.test(value) || value.startsWith("mailto:") || value.startsWith("tel:");
    };

    return (
      <RouterNavLink
        ref={ref}
        to={to}
        className={({ isActive, isPending }) =>
          cn(className, isActive && activeClassName, isPending && pendingClassName)
        }
        onClick={(event) => {
          onClick?.(event);
          if (
            event.defaultPrevented ||
            event.button !== 0 ||
            event.metaKey ||
            event.altKey ||
            event.ctrlKey ||
            event.shiftKey ||
            props.target === "_blank" ||
            isExternalTo(to)
          ) {
            return;
          }

          // Force client-side route transitions for app menu links.
          event.preventDefault();
          navigate(to, {
            replace: props.replace,
            state: props.state,
            relative: props.relative,
            preventScrollReset: props.preventScrollReset,
            viewTransition: props.viewTransition,
          });
        }}
        {...props}
      />
    );
  },
);

NavLink.displayName = "NavLink";

export { NavLink };
