import { type NavLinkRenderProps, Link as RouterLink, NavLink as RouterNavLink } from 'react-router-dom';

type RouterLinkProps = React.ComponentProps<typeof RouterLink>;
type RouterNavLinkProps = React.ComponentProps<typeof RouterNavLink>;
type ExternalLinkProps = {
  external?: false | true;
} & (
  | ({
      routerLinkComponent: typeof RouterLink;
    } & RouterLinkProps)
  | ({
      routerLinkComponent: typeof RouterNavLink;
    } & RouterNavLinkProps)
);

// 包裹 router Link/NavLink 组件, 支持 external link (external 为 true 时渲染为 a 标签)
function ExternalLink({
  routerLinkComponent: RouterLinkComponent,
  to,
  external = false,
  children,
  ...rest
}: ExternalLinkProps) {
  if (external) {
    return (
      // @ts-expect-error
      <a href={to} {...rest}>
        {/* @ts-expect-error */}
        {children}
      </a>
    );
  }
  return (
    // @ts-ignore
    <RouterLinkComponent to={to} {...rest}>
      {/* @ts-expect-error */}
      {children}
    </RouterLinkComponent>
  );
}

export interface LinkProps extends RouterLinkProps {
  external?: false | true;
}

export function Link({ ...props }: LinkProps) {
  return <ExternalLink routerLinkComponent={RouterLink} {...props} />;
}

export interface NavLinkProps extends Omit<RouterNavLinkProps, 'className'> {
  className?: string | ((props: Partial<NavLinkRenderProps>) => string | undefined);
  external?: false | true;
}

export function NavLink({ className = '', ...rest }: NavLinkProps) {
  // NavLink#className 支持 function
  const classes = rest.external && typeof className === 'function' ? className({}) : className;
  return <ExternalLink routerLinkComponent={RouterNavLink} className={classes} {...rest} />;
}
