// Copyright 1999-2020. Plesk International GmbH. All rights reserved.
import classNames from 'classnames';
import React, { useContext } from 'react';
import { isRtl } from '../../utils';
import { CLS_PREFIX } from '../../constants';
import OnDarkContext from '../OnDarkContext';
import { safeInvoke } from '../utils';
import Icon from '../Icon';

/**
 * FIXME: With the following code all @ts-ignore comments can be removed, but react-docgen cannot parse it.
 * const Link = <P extends any>({ ... }: LinkProps<P>) => {
 */

/**
 * `Link` is used for navigation purposes.
 * @since 1.9.0
 */
const Link = ({
  baseClassName = `${CLS_PREFIX}link`,
  className,
  onClick,
  disabled = false,
  pseudo = false,
  component,
  children,
  onKeyDown,
  ...other
}) => {
  const Component = component ? component : 'a';
  const onDark = useContext(OnDarkContext);
  const props = { ...other,
    onClick,
    className: classNames(baseClassName, className, {
      [`${baseClassName}--disabled`]: disabled,
      [`${baseClassName}--pseudo`]: pseudo,
      [`${baseClassName}--on-dark`]: onDark
    })
  };
  const {
    target
  } = other;
  const external = !pseudo && target === '_blank';

  if (external && !props.rel) {
    props.rel = 'noopener noreferrer';
  }

  if (disabled) {
    props.onClick = e => e.preventDefault();

    props.tabIndex = -1;
  } // accessibility


  if (onClick) {
    props.tabIndex = props.tabIndex || 0;

    props.onKeyDown = e => {
      if (e.key === 'Enter') {
        e.preventDefault();
        e.currentTarget.click();
      }

      safeInvoke(onKeyDown, e);
    };
  }

  return (
    /*#__PURE__*/
    // @ts-ignore
    React.createElement(Component, props, children, external && /*#__PURE__*/React.createElement(Icon, {
      flipHorizontal: isRtl(),
      name: "arrow-diagonal-out",
      className: `${baseClassName}__external-icon`
    }))
  );
};

export default Link;