// @flow
import React from 'react';
import styled, { css } from 'styled-components';
import type { PatchworkComponent } from '../../../types';
import type { TertiaryButtonProps } from './tertiary-button.proptypes';
import { getPaletteColor } from '../../../mixins/branding';
import { getSpacingRules } from '../../../mixins/spacing';
import {
  getFontFamily,
  getFontWeight,
  getFontSize,
} from '../../../mixins/typography';
import {
  getBorderRadius,
  getBorderColor,
  getBorderColorHover,
  getBorderColorActive,
} from './tertiary-button.css-rules';
import {
  FOCUS_VISIBLE_SELECTOR,
  getBaseFocusState,
  focusedBoxShadow,
  focusedBorderShadow,
  focusedBorderColor,
} from '../../../mixins/focus';

const getCommonStyles = css`
  && {
    display: inline-block;
    min-width: 80px;
    height: 32px;
    border-width: 1px;
    border-style: solid;
    border-radius: ${getBorderRadius};
    background-color: ${getPaletteColor('white')};
    border-color: ${getBorderColor};
    color: ${getPaletteColor('greyscale-darker')};
    text-decoration: none;
    font-size: ${getFontSize};
    font-family: ${getFontFamily};
    font-weight: ${getFontWeight};
    padding: 0 15px;
    ${getBaseFocusState({})}
  }
  ${FOCUS_VISIBLE_SELECTOR} {
    border-color: transparent;
    box-shadow: ${focusedBoxShadow},
      ${focusedBorderShadow} ${focusedBorderColor};
  }
  &:hover {
    border-color: ${getBorderColorHover};
  }
  &:active {
    color: ${getPaletteColor('greyscale-black')};
    border-color: ${getBorderColorActive};
  }
  &[disabled] {
    color: ${getPaletteColor('greyscale-medium')};
    border-color: ${getPaletteColor('greyscale-light')};
  }
`;
const ActualButton: PatchworkComponent<TertiaryButtonProps> = styled.button.attrs(
  props => ({
    type: 'button',
    style: getSpacingRules(props),
    bold: 'true',
    fontSize: 'f0',
  }),
)`
  ${getCommonStyles}
  line-height: 100%;
`;

const LinkButton: PatchworkComponent<TertiaryButtonProps> = styled.a.attrs(
  props => ({
    style: getSpacingRules(props),
    bold: 'true',
    fontSize: 'f0',
  }),
)`
  ${getCommonStyles}
  line-height: 32px;
  text-align: center;
  text-decoration: none;
`;

export const TertiaryButton = ({
  href,
  target,
  onClick,
  disabled,
  ...props
}: TertiaryButtonProps) =>
  href == null ? (
    <ActualButton onClick={onClick} disabled={disabled} {...props} />
  ) : (
    <LinkButton
      href={!disabled ? href : null}
      disabled={disabled}
      target={target}
      {...props}
    />
  );

TertiaryButton.displayName = 'TertiaryButton';
