import React, { Children, cloneElement, isValidElement } from 'react';
import PropTypes from 'prop-types';

import Card from './Card';
import CardIcon from './Icon';
import SectionTitle from './SectionTitle';
import SectionBody from './SectionBody';
import CardBanner from './Banner';
import SectionFooter from './SectionFooter';
import CardSection from './Section';
import './cards.scss';

const MAX_ITEMS_BY_ROW = 4;

const propTypes = {
  /** @ignore */
  className: PropTypes.bool,
  /** @ignore */
  children: PropTypes.node,
  /**
  * Max number of card per row
  */
  itemsPerRow: PropTypes.number,
  horizontal: PropTypes.bool
};

const defaultProps = {
  className: undefined,
  children: null,
  itemsPerRow: null,
  horizontal: false
};

const Cards = ({ className, children, itemsPerRow, horizontal, ...rest }) => {
  const childrenArray = Children.toArray(children);
  const cleanChildren = childrenArray.filter(child => isValidElement(child));
  const resultItemsPerRow = itemsPerRow
    ? Math.min(itemsPerRow, MAX_ITEMS_BY_ROW) : Math.min(cleanChildren.length, MAX_ITEMS_BY_ROW);
  const resultChildren = childrenArray
    .map((child, row) => {
      const { type: { componentName } } = child;
      if (!isValidElement(child)) {
        return child;
      }
      switch (componentName) {
        case 'Card':
          return cloneElement(child, { itemsPerRow: resultItemsPerRow, key: `item-${row}`, horizontal });
        default:
          return child;
      }
    });

  return (
    <div className={className} styleName="container" {...rest}>
      {resultChildren}
    </div>
  );
};

Cards.propTypes = propTypes;
Cards.defaultProps = defaultProps;

Cards.Card = Card;
Cards.Icon = CardIcon;
Cards.Banner = CardBanner;
Cards.Section = CardSection;
Cards.SectionTitle = SectionTitle;
Cards.SectionBody = SectionBody;
Cards.SectionFooter = SectionFooter;
export default Cards;
