/* @flow */
/* eslint-disable quote-props */

import * as React from 'react'
import { Column, Row } from '@siteone/atoms'
import config from '../../../config'

const { gutter, gutterSmall } = config

type Props = {
  fractor?: '1' | '2' | '3' | '4',
  narrow?: boolean,
  children: React.ChildrenArray<React.Element<any>>,
  gutter?: 'small' | 'smallVertical' | 'smallHorizontal' | 'big',
}

const columnLayout = {
  '1': {
    s: '100%',
  },
  '2': {
    s: '100%',
    ns: '50%',
  },
  '3': {
    s: '100%',
    m: '50%',
    l: 'third',
  },
  '3ns': {
    s: '100%',
    ns: 'third',
  },
  '4': {
    s: '100%',
    m: '50%',
    l: '25%',
  },
}

const gutterSettings = {
  small: {
    row: {
      negativeMargin: gutterSmall,
    },
    column: {
      padding: gutterSmall,
    },
  },
  smallVertical: {
    row: {
      negativeMarginHorizontal: gutter,
      negativeMarginVertical: gutterSmall,
      negativeMargin: null,
    },
    column: {
      paddingHorizontal: gutter,
      paddingVertical: gutterSmall,
      padding: null,
    },
  },
  smallHorizontal: {
    row: {
      negativeMarginHorizontal: gutterSmall,
      negativeMarginVertical: gutter,
      negativeMargin: null,
    },
    column: {
      paddingHorizontal: gutterSmall,
      paddingVertical: gutter,
      padding: null,
    },
  },
  big: {
    row: { negativeMargin: gutter },
    column: { padding: gutter },
  },
}

const FractionalGrid = ({
  fractor, narrow, children, gutter, ...rest
}: Props) => {
  const { row, column } = gutterSettings[gutter] || gutterSettings.big
  const typography = narrow ? 'measure-max' : undefined
  return (
    <Row {...row} {...rest}>
      {children &&
        React.Children.toArray(children).map(child => (
          <Column width={columnLayout[fractor]} {...column} typography={typography} key={child.key}>
            {child}
          </Column>
        ))}
    </Row>
  )
}

FractionalGrid.defaultProps = {
  fractor: '1',
  narrow: false,
  gutter: 'big',
}

export default FractionalGrid
