import React from 'react';
import { color } from 'styled-system';
import { styled } from '../../styles';

// eslint-disable-next-line no-useless-escape
const urlRegex = /[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/;

export interface LinkProps
  extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
  href?: string;
}

const LinkComponent = ({ href, ...rest }: LinkProps) => {
  const isExternal = href && href.match(urlRegex);
  let linkProps = {};

  if (isExternal) {
    linkProps = {
      target: '_blank',
      rel: 'noopener noreferrer',
    };
  }

  return <a href={href} {...linkProps} {...rest} />;
};

export const Link = styled(LinkComponent)(color, ({ theme }) => ({
  textDecoration: 'none',
  ...theme.links,

  '&:hover, &:focus': {
    textDecoration: 'none',
  },
}));
