// @flow
import styled from 'styled-components';
import type { BoxProps } from './box.proptypes';
import type { PatchworkComponent, ThemeProps } from '../../types';
import { getSpacingRules } from '../../mixins/spacing';
import { getStackedRules, getStackedDisplay } from '../../mixins/stacking';
import { getPaletteColor } from '../../mixins/branding';
import type { BrandProps } from '../../mixins/branding';
import {
  getHideDisplaySm,
  legacyGetHideDisplayMd,
  getHideDisplayMd,
  getHideDisplayLg,
  getHideDisplayXl,
} from '../../mixins/hide';
import { bpMedium, bpLarge, bpXLarge } from '../../breakpoints';

const style = ({
  theme,
  colorName,
  spacing,
  stacked,
  justify,
  align,
}: BoxProps & ThemeProps & BrandProps) => {
  const backgroundRules = () =>
    colorName ? { background: getPaletteColor(colorName)({ theme }) } : {};

  return {
    ...getSpacingRules({ theme, spacing }),
    ...getStackedRules({ stacked, justify, align }),
    ...backgroundRules(),
  };
};

const medium = parseInt(bpMedium, 10);
const large = parseInt(bpLarge, 10);
const xlarge = parseInt(bpXLarge, 10);

export const Box: PatchworkComponent<BoxProps> = styled.div.attrs(props => ({
  style: style(props),
}))`
  display: ${getStackedDisplay};

  @media (min-width: 0px) and (max-width: ${medium - 1}px) {
    display: ${getHideDisplaySm};
  }

  @media (min-width: ${medium}px) and (max-width: ${large - 1}px) {
    display: ${getHideDisplayMd};
  }

  @media (min-width: ${medium}px) {
    display: ${legacyGetHideDisplayMd};
  }

  @media (min-width: ${large}px) and (max-width: ${xlarge - 1}px) {
    display: ${getHideDisplayLg};
  }

  @media (min-width: ${xlarge}px) {
    display: ${getHideDisplayXl};
  }
`;

Box.displayName = 'Box';
