// @flow
import React, { type StatelessFunctionalComponent } from 'react';
import styled from 'styled-components';
import type { LinkProps } from './link.proptypes';
import { getLinkColor, getLinkFontSize } from './link.css-rules';
import {
  getFontFamily,
  getFontWeight,
  getFontSize,
} from '../../../mixins/typography';
import {
  FOCUS_VISIBLE_SELECTOR,
  getBaseFocusState,
  focusedBoxShadow,
  focusedBorderShadow,
  focusedBorderColor,
} from '../../../mixins/focus';

const ActualLink: StatelessFunctionalComponent<LinkProps> = styled.a`
  font-size: ${getLinkFontSize};
  outline: none;
  /* More specific because of high specificity in Terminal */
  &&& {
    color: ${getLinkColor};
    text-decoration: underline;
    ${getBaseFocusState({ hoverTransition: false, activeTransition: false })}
    ${FOCUS_VISIBLE_SELECTOR} {
      border-radius: 3px;
      box-shadow: ${focusedBorderShadow({ inset: false })} ${focusedBorderColor},
        ${focusedBoxShadow};
    }
  }
`;

const ButtonLink: StatelessFunctionalComponent<LinkProps> = styled.button.attrs(
  ({ type = 'button' }) => ({
    type,
    fontSize: 'f1',
  }),
)`
  border: none;
  background: inherit;
  outline: none;
  padding: 0;
  font-family: ${getFontFamily};
  font-weight: ${getFontWeight};
  font-size: ${getFontSize};
  /* More specific because of high specificity in Terminal */
  &&& {
    color: ${getLinkColor};
    text-decoration: underline;
    ${getBaseFocusState({ hoverTransition: false, activeTransition: false })}
    ${FOCUS_VISIBLE_SELECTOR} {
      border-radius: 3px;
      box-shadow: ${focusedBorderShadow({ inset: false })} ${focusedBorderColor},
        ${focusedBoxShadow};
    }
  }
`;

export const Link = ({ href, target, onClick, type, ...props }: LinkProps) =>
  onClick == null || href != null ? (
    <ActualLink href={href} onClick={onClick} target={target} {...props} />
  ) : (
    <ButtonLink onClick={onClick} type={type} {...props} />
  );

Link.displayName = 'Link';
