import React, { HTMLAttributes } from 'react';
import './silke-link.scss';
import { LinkProps, Link } from 'react-router-dom';
import { SilkeIcon, SilkeIcons } from '../silke-icon';

const getRelFromTarget = (target?: string): 'noopener noreferrer' | undefined => {
  return !target ||
    target.toLowerCase() === '_self' ||
    target.toLowerCase() === '_top' ||
    target.toLowerCase() === '_parent'
    ? undefined
    : 'noopener noreferrer';
};

const getClassNames = (
  className?: string,
  standalone?: boolean,
  kind?: 'primary' | 'secondary',
): string => {
  const cn = className ? ['silke-link', className] : ['silke-link'];
  if (standalone) {
    cn.push('silke-link--standalone');
  }
  if (kind) {
    cn.push(kind);
  }

  return cn.join(' ');
};

interface LinkChildProps {
  external?: boolean;
  icon?: SilkeIcons;
  children?: React.ReactNode;
}

const LinkChild = (props: LinkChildProps) => {
  const { children, icon, external } = props;
  const displayIcon = !!(icon || external);

  return (
    <>
      {displayIcon ? <span>{children}</span> : children}
      {displayIcon && (
        <SilkeIcon
          className="silke-link-icon"
          icon={icon || 'link.external'}
          style={{ fontSize: '.8em' }}
        />
      )}
    </>
  );
};

interface SilkeLinkProps
  extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'children'>,
    LinkChildProps {
  standalone?: boolean;
  kind?: 'primary' | 'secondary';
}

export const SilkeLink: React.FunctionComponent<SilkeLinkProps> = ({
  kind = 'primary',
  ...props
}: SilkeLinkProps) => {
  const { target, standalone, className, external, children, icon, ...rest } = props;
  const rel = getRelFromTarget(target);
  return (
    <a rel={rel} target={target} className={getClassNames(className, standalone, kind)} {...rest}>
      <LinkChild external={external} icon={icon}>
        {children}
      </LinkChild>
    </a>
  );
};

interface SilkeRouterLinkProps extends Omit<LinkProps, 'children'>, LinkChildProps {
  standalone?: boolean;
}

export const SilkeRouterLink: React.FunctionComponent<SilkeRouterLinkProps> = (
  props: SilkeRouterLinkProps,
) => {
  const { className, standalone, external, children, icon, ...rest } = props;
  return (
    <Link {...rest} className={getClassNames(className, standalone)}>
      <LinkChild icon={icon} external={external}>
        {children}
      </LinkChild>
    </Link>
  );
};

export interface SilkeButtonLinkProps extends HTMLAttributes<HTMLButtonElement> {
  standalone?: boolean;
  icon?: SilkeIcons;
}

export const SilkeButtonLink = (props: SilkeButtonLinkProps) => {
  const { className, standalone, icon, children, ...rest } = props;

  return (
    <button type="button" {...rest} className={getClassNames(className, standalone)}>
      <LinkChild icon={icon}>{children}</LinkChild>
    </button>
  );
};
