// @flow
import React from 'react';
import styled from 'styled-components';
import { Box } from '../../../primitives/box/index';
import { getFontFamily, getFontWeight } from '../../../mixins/typography';
import { textIconButtonProptypes } from './text-icon-button.proptypes';
import type {
  TextIconButtonProps,
  IconType,
} from './text-icon-button.proptypes';
import { SmallArrowRight } from '../../icon/small-arrow-right';
import { Add } from '../../icon/add';
import {
  getLinkHoverColor,
  getLinkActiveColor,
  getLinkColor,
} from './text-button-with-icon.css-rules';
import {
  FOCUS_VISIBLE_SELECTOR,
  getBaseFocusState,
  focusedBoxShadow,
  focusedBorderShadow,
  focusedBorderColor,
  focusedBorderRadius,
} from '../../../mixins/focus';

const BaseAnchor = styled.a.attrs(() => ({
  bold: 'true',
}))`
  && {
    color: ${getLinkColor};
    font-family: ${getFontFamily};
    font-weight: ${getFontWeight};
    text-decoration: none;
    cursor: pointer;
    svg {
      vertical-align: middle;
    }
    ${getBaseFocusState({ hoverTransition: false, activeTransition: false })}
  }
  ${FOCUS_VISIBLE_SELECTOR} {
    & > div {
      box-shadow: ${focusedBorderShadow({ inset: false })} ${focusedBorderColor},
        ${focusedBoxShadow};
      border-radius: ${focusedBorderRadius};
    }
    svg > g {
      fill: ${getLinkActiveColor};
    }
  }
  &:hover {
    color: ${getLinkHoverColor};
    text-decoration: underline;
    svg > g {
      fill: ${getLinkHoverColor};
    }
  }
  &:active {
    color: ${getLinkActiveColor};
    text-decoration: underline;
    svg > g {
      fill: ${getLinkActiveColor};
    }
  }
`;

const getIcon = (icon: IconType) => {
  switch (icon) {
    case 'add':
      return <Add />;
    case 'small-arrow-right':
      return <SmallArrowRight />;
    default:
      return null;
  }
};

/**
 * Important: Due to our dependence on Icomoon, we cannot have an element
 * whose class name contains `icon-` in the middle.
 * We need the `Icon` part to be at the end instead of at the start or middle
 * because React auto-generates class names based on the component's displayName.
 */
export const TextButtonWithIcon = (props: TextIconButtonProps) => (
  <BaseAnchor href={props.href} target={props.target}>
    <Box stacked="row" align="center">
      {props.position === 'left' && (
        <Box spacing="mr1" stacked="row" align="center">
          {getIcon(props.icon)}
        </Box>
      )}
      <Box>{props.children}</Box>
      {props.position === 'right' && (
        <Box spacing="ml1" stacked="row" align="center">
          {getIcon(props.icon)}
        </Box>
      )}
    </Box>
  </BaseAnchor>
);

TextButtonWithIcon.displayName = 'TextButtonWithIcon';
TextButtonWithIcon.propTypes = textIconButtonProptypes;
