import { NavigateAway as NavigateAwayIcon } from '@transferwise/icons';
import { clsx } from 'clsx';
import { useIntl } from 'react-intl';
import { PrimitiveAnchor, PrimitiveButton } from '../primitives';
import type { PrimitiveAnchorProps, PrimitiveButtonProps } from '../primitives';

import { LinkLarge, LinkDefault, Typography } from '../common';

import messages from './Link.messages';

export type Props = PrimitiveAnchorProps &
  Pick<PrimitiveButtonProps, 'onClick'> & { type?: LinkLarge | LinkDefault };

/**
 * Standard Link component with navigate away icon
 *
 * Documentation: https://transferwise.github.io/neptune-web/components/content/Link
 */
const Link = ({
  className,
  children,
  href,
  target,
  type = Typography.LINK_DEFAULT,
  'aria-label': ariaLabel,
  onClick,
  disabled,
  ...props
}: Props) => {
  const { formatMessage } = useIntl();
  const isButton = Boolean(onClick) && href === undefined;
  const isBlank = target === '_blank';

  const classNames = clsx(
    'np-link',
    'd-inline-flex',
    {
      [`np-text-${type}`]: type,
      'np-link--disabled': disabled,
    },
    className,
  );

  return isButton ? (
    <PrimitiveButton
      type="button"
      aria-label={ariaLabel}
      className={clsx(classNames, 'btn-unstyled')}
      disabled={disabled}
      onClick={onClick}
    >
      {children}
    </PrimitiveButton>
  ) : (
    <PrimitiveAnchor
      href={href}
      target={target}
      className={classNames}
      aria-label={ariaLabel}
      rel={isBlank ? 'noreferrer' : undefined}
      disabled={disabled}
      onClick={onClick}
      {...props}
    >
      {children} {isBlank && <NavigateAwayIcon title={formatMessage(messages.opensInNewTab)} />}
    </PrimitiveAnchor>
  );
};

export default Link;
