import React, { CSSProperties, ReactNode } from 'react';
import classNames from 'clsx';
import { useTheme } from '@mui/material/styles';

import styles from './GridList.module.scss';

type Props = {
  children: ReactNode;
  gap?: number;
  rowCount: number;
  fullWidth?: boolean;
  direction?: 'row' | 'column';
};

function GridList({ children, fullWidth = false, direction = 'column', rowCount, gap = 3 }: Props) {
  const theme = useTheme();
  const childrenList = (Array.isArray(children) ? children : [children]).filter(Boolean);
  const fixedRowCount = Math.max(1, Math.min(childrenList.length, rowCount));
  const columnCount = Math.ceil(childrenList.length / fixedRowCount);

  return (
    <div
      style={
        {
          gap: theme.spacing(gap),
          '--internal-row-count': fixedRowCount,
          '--internal-column-count': columnCount,
        } as CSSProperties
      }
      className={classNames(styles.GridContainer, {
        [styles.GridContainer___fullWidth]: fullWidth,
        [styles.GridContainer___row]: direction === 'row',
        [styles.GridContainer___column]: direction === 'column',
      })}
    >
      {childrenList.map((child, key) => (
        <div key={`${+key}`}>{child}</div>
      ))}
    </div>
  );
}

GridList.displayName = 'GridList';

export default GridList;
