// @flow
import React, { type ComponentType, forwardRef } from 'react';
import styled, { css } from 'styled-components';
import { getPaletteColor } from '../../../mixins/branding';
import { getStackedRules } from '../../../mixins/stacking';
import { getStackeeRules } from '../../../mixins/stackee';
import {
  getBaseFocusState,
  FOCUS_VISIBLE_SELECTOR,
  focusedBoxShadow,
  focusedBorderShadow,
  focusedBorderColor,
} from '../../../mixins/focus';
import type { CardProps } from './card.proptypes';
import {
  getCardSpacingRules,
  getBoxShadowColor,
  getCardFontSize,
  getCardBorderRadius,
} from './card.css-rules';
import { UnstyledButton } from '../../behaviors/unstyled-button';

const sharedStyles = css`
  background-color: ${getPaletteColor('white')};
  border-radius: ${getCardBorderRadius};
  box-shadow: 0 5px 15px 0 ${getBoxShadowColor};
  display: block;
  font-size: ${getCardFontSize};
  ${getCardSpacingRules};
  ${getStackedRules};
  ${getStackeeRules};
`;

const CardDiv = styled.div`
  ${sharedStyles}
`;

const CardLink = styled.a`
  color: inherit;
  outline: none;
  text-decoration: inherit;
  ${getBaseFocusState}
  ${FOCUS_VISIBLE_SELECTOR} {
    box-shadow: ${focusedBorderShadow({ inset: false })} ${focusedBorderColor},
      ${focusedBoxShadow};
  }

  ${sharedStyles};
`;

const CardButton = styled(UnstyledButton)`
  width: 100%;
  line-height: inherit;
  ${sharedStyles}
`;

export const Card: ComponentType<CardProps> = forwardRef(
  (props: CardProps, ref) => {
    if (props.href != null) {
      return <CardLink ref={ref} {...props} />;
    }

    if (props.onClick) {
      return <CardButton ref={ref} {...props} />;
    }

    return <CardDiv ref={ref} {...props} />;
  },
);

Card.displayName = 'Card';
