import React from 'react';
import Link from 'next/link';
import StyledAnchor from './link.styles';

interface NextLinkProps {
  href: string; // The path inside pages directory
  children: React.ReactNode;
  as?: string; // The path that will be rendered in the browser URL bar. Used for dynamic routes
  scroll?: boolean; // Scroll to the top of the page after a navigation
  target?: string;
  prefetch?: boolean; // Prefetch the page in the background
  replace?: boolean; // Replace the current history state instead of adding a new url into the stack
  isExternal?: boolean; // Does the link navigate outside this app?
  ariaLabel?: string;
  ariaLabelledby?: string;
  ariaHidden?: boolean;
  clickCategory?: string; // GTM tracking Category
  clickAction?: string; // GTM tracking Action
  clickLabel?: string; // GTM tracking Label
  onClick?: () => void; // click callback
}

export const isAbsoluteUrl = (url: string): boolean => {
  if (url !== null) {
    return url.includes('://') || url.includes('//') || url.includes('mailto');
  }

  return false;
}

export const NextLink: React.FC<NextLinkProps> = ({
  href,
  as,
  children,
  scroll = true,
  target,
  replace = false,
  isExternal = false,
  ariaLabel,
  ariaLabelledby,
  ariaHidden,
  clickCategory,
  clickAction,
  clickLabel,
  onClick,
  ...rest
}) => {
  if (isAbsoluteUrl(href) || isExternal) {
    return (
      <StyledAnchor
        href={`${href}`}
        target={target || '_blank'}
        rel="noopener noreferrer"
        aria-labelledby={ariaLabelledby}
        aria-label={ariaLabel}
        aria-hidden={ariaHidden}
        data-click-category={clickCategory}
        data-click-action={clickAction}
        data-click-label={clickLabel}
        onClick={onClick}
        {...rest}
      >
        {children}
      </StyledAnchor>
    );
  }

  return (
    <Link href={`${href}`} as={as} replace={replace} scroll={scroll} passHref {...rest} data-click-category={clickCategory} data-click-action={clickAction} data-click-label={clickLabel}>
      <StyledAnchor aria-labelledby={ariaLabelledby} aria-label={ariaLabel} aria-hidden={ariaHidden} target={target} data-click-category={clickCategory} data-click-action={clickAction} data-click-label={clickLabel} onClick={onClick}>
        {children}
      </StyledAnchor>
    </Link>
  );
};

NextLink.displayName = 'NextLink';

export default NextLink;
