import { array, node, number, oneOfType, string } from 'prop-types';

import Box from '../Box/index';
import css from '@styled-system/css';
import { get } from 'styled-system';
/** @jsx jsx */
import { jsx } from '@emotion/core';
import { supportsFlexGap } from '../../../utils/featureDetect';
import { useTheme } from 'emotion-theming';

const flexGapSupported = supportsFlexGap();

const Shelf = ({
  gap: gapProp = 'gutter',
  rowGap = gapProp,
  children,
  justifyContent,
  alignItems = 'center',
  flexWrap = 'wrap',
  ...wrapperProps
}) => {
  const theme = useTheme();

  if (flexGapSupported) {
    return (
      <Box
        display="flex"
        alignItems={alignItems}
        flexWrap={flexWrap}
        justifyContent={justifyContent}
        css={css({
          columnGap: gapProp,
          rowGap: rowGap,
        })}
        {...wrapperProps}
      >
        {children}
      </Box>
    );
  }

  let gap = gapProp;
  if (Array.isArray(gap)) {
    gap = gap[gap.length - 1];
  }
  let space = get(theme, `space.${gap}`, gap);

  return (
    // extra wrappper because of negative margins
    <Box {...wrapperProps}>
      <div
        css={{
          marginLeft: `-${space}px`,
          marginBottom: `-${space}px`,
          width: `calc(100% + ${space + 1}px)`,
          '> *': {
            marginLeft: space,
            marginBottom: space,
          },
          display: 'flex',
          justifyContent,
          alignItems,
          flexWrap,
        }}
      >
        {children}
      </div>
    </Box>
  );
};

Shelf.propTypes = {
  gap: oneOfType([string, number, array]),
  rowGap: oneOfType([string, number, array]),
  flexWrap: oneOfType([string, array]),
  justifyContent: string,
  alignItems: string,
  children: node,
};

export default Shelf;
