import React from 'react';
import PropTypes from 'prop-types';
import './styles/Grid.scss';
import { createNamespace } from '../../tools/namingTools';
import { SMALL, LARGE } from '../../constants/sizes';

const n = createNamespace('Grid');

const Grid = ({
    maxCol,
    minWidth,
    maxWidth,
    spacing,
    stretch,
    children,
    itemClass,
    rowClass,
    gutterWidth,
    gutterHeight,
    gridRef
}) => {
    const gridItemList = children ? React.Children.toArray(children).filter(child => child) : null;
    const rowModifiers = [
        gutterWidth && `gutter-width-${gutterWidth}`,
        gutterHeight && `gutter-height-${gutterHeight}`
    ];

    if (!gridItemList || !gridItemList.length) {
        return null;
    }

    const renderGridItem = child => {
        const itemModifiers = [
            maxCol,
            gutterWidth && `gutter-width-${gutterWidth}`,
            gutterHeight && `gutter-height-${gutterHeight}`
        ];
        const extraStyle = {};

        if (minWidth) {
            extraStyle.style = { minWidth };
        }
        if (maxWidth) {
            extraStyle.style = { maxWidth };
        }
        if (stretch) {
            itemModifiers.push('stretch');
        }

        return <div {...n('item', itemModifiers).withClass(itemClass).withTestId().withE2EId().props} {...extraStyle}>{child}</div>;
    };

    return (
        <div
            {...n('row', rowModifiers).withClass(rowClass).withE2EId().props}
            style={{ justifyContent: spacing }}
            ref={gridRef}
        >
            {React.Children.map(gridItemList, renderGridItem)}
        </div>
    );
};

Grid.propTypes = {
    maxCol: PropTypes.number,
    minWidth: PropTypes.string,
    maxWidth: PropTypes.string,
    spacing: PropTypes.string,
    stretch: PropTypes.bool,
    itemClass: PropTypes.string,
    rowClass: PropTypes.string,
    gutterWidth: PropTypes.oneOf([SMALL.value]),
    gutterHeight: PropTypes.oneOf([LARGE.value]),
    gridRef: PropTypes.object
};

Grid.defaultProps = {
    maxCol: 3,
    minWidth: '',
    maxWidth: '',
    spacing: 'flex-start',
    stretch: false,
    itemClass: null,
    rowClass: null,
    gutterWidth: null,
    gutterHeight: null,
    gridRef: null
};

export default Grid;
