// @flow
import React from 'react';
import styled, { keyframes } from 'styled-components';
import type { MessageLevel, MessageProps } from './message.proptypes';
import { Box } from '../../../primitives';
import { Text } from '../../typography/text';
import type { ColorPaletteColorNameKey } from '../../../mixins/branding';

type MessageColors = {
  bgColor: ColorPaletteColorNameKey,
  fgColor: ColorPaletteColorNameKey,
};

const messageColor: {
  info: MessageColors,
  error: MessageColors,
  success: MessageColors,
} = {
  info: {
    bgColor: 'info-bg',
    fgColor: 'greyscale-black',
  },
  error: {
    bgColor: 'error-bg',
    fgColor: 'error-fg',
  },
  success: {
    bgColor: 'success-bg',
    fgColor: 'success-fg',
  },
};

const getBackgroundColorName = (
  level: MessageLevel,
): ColorPaletteColorNameKey => {
  switch (level) {
    case 'error':
      return messageColor.error.bgColor;
    case 'success':
      return messageColor.success.bgColor;
    default:
      return messageColor.info.bgColor;
  }
};

const getForegroundColorName = (
  level: MessageLevel,
): ColorPaletteColorNameKey => {
  switch (level) {
    case 'error':
      return messageColor.error.fgColor;
    case 'success':
      return messageColor.success.fgColor;
    default:
      return messageColor.info.fgColor;
  }
};

const fadeIn = keyframes`
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
`;

const StyledMessageContainer = styled(Box)`
  animation: ${fadeIn} 0.5s linear;
  border-radius: 6px;
  text-align: left;
`;

const StyledTitle = styled(Text)`
  margin-bottom: 5px;
`;

export const Message = ({
  children,
  level = 'info',
  spacing,
  title,
  ...rest
}: MessageProps) => {
  const space = ['pv1', 'ph2'];
  if (typeof spacing === 'string') {
    space.push(spacing);
  } else if (spacing != null) {
    space.concat(spacing);
  }
  return (
    <StyledMessageContainer
      colorName={getBackgroundColorName(level)}
      spacing={space}
      {...rest}
    >
      {title != null && (
        <StyledTitle
          bold
          colorName={getForegroundColorName(level)}
          fontSize="f1"
        >
          {title}
        </StyledTitle>
      )}
      <Text
        colorName={getForegroundColorName(level)}
        fontSize="f1"
        spacing="m0"
      >
        {children}
      </Text>
    </StyledMessageContainer>
  );
};

Message.displayName = 'Message';
