// @flow
import React, { forwardRef, type ComponentType } from 'react';
import styled, { css } from 'styled-components';
import type { SecondaryButtonProps } from './secondary-button.proptypes';
import { secondaryButtonPropTypes } from './secondary-button.proptypes';
import { getPaletteColor } from '../../../mixins/branding';
import { getSpacingRules } from '../../../mixins/spacing';
import {
  getFontFamily,
  getFontWeight,
  getFontSize,
} from '../../../mixins/typography';
import { getBorderRadius } from './secondary-button.css-rules';
import {
  FOCUS_VISIBLE_SELECTOR,
  transitionInstant,
  getBaseFocusState,
  focusedBoxShadow,
  focusedBorderShadow,
  focusedBorderColor,
  activeBackgroundColor,
  hoverBackgroundColor,
} from '../../../mixins/focus';

const getCommonStyles = css`
  && {
    display: inline-block;
    height: 48px;
    border-width: 0;
    padding: 0 20px;
    background: transparent;
    color: ${getPaletteColor('greyscale-darker')};
    text-decoration: none;
    font-size: ${getFontSize};
    font-family: ${getFontFamily};
    font-weight: ${getFontWeight};
    border-radius: ${getBorderRadius};
    ${getBaseFocusState({ activeTransition: false })}
  }
  ${FOCUS_VISIBLE_SELECTOR} {
    transition: ${transitionInstant};
    box-shadow: ${focusedBoxShadow},
      ${focusedBorderShadow} ${focusedBorderColor};
  }
  &:hover {
    background-color: ${hoverBackgroundColor};
  }
  &:active {
    background-color: ${activeBackgroundColor};
  }
  &[disabled] {
    &:hover {
      cursor: default;
      background-color: transparent;
    }
    color: ${getPaletteColor('greyscale-medium')};
  }
`;

const ActualButton = styled.button.attrs(props => ({
  type: props.type || 'button',
  style: getSpacingRules(props),
  bold: 'true',
}))`
  ${getCommonStyles}
  line-height: 100%;
`;

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

export const SecondaryButton: ComponentType<SecondaryButtonProps> = forwardRef(
  (props: SecondaryButtonProps, ref) => {
    return props.href === undefined ? (
      <ActualButton {...props} ref={ref} />
    ) : (
      <LinkButton {...props} ref={ref} />
    );
  },
);

SecondaryButton.propTypes = secondaryButtonPropTypes;
SecondaryButton.displayName = 'SecondaryButton';
