import React, { useEffect } from 'react';
import { evenlyDistrubuteArrayOfArrays } from '../../helpers/evenlyDistrubuteArrayOfArrays';
import SelectableBlock from '../SelectableBlock';
import { BlockColumnWrapper, InnerGrid, SelectableBlockSpacer } from './styles';

export type Block = {
  altText?: string;
  src: string;
  isSelected: boolean;
};

type BlockColumnLayoutProps = {
  blocks: Block[];
  numColumns: number;
  columnWidth: number;
  onBlockClick: (src: string) => void;
};

const BlockColumnLayout: React.FC<BlockColumnLayoutProps> = ({
  blocks,
  columnWidth,
  numColumns,
  onBlockClick,
}) => {
  const [splitColumns, setSplitColumns] = React.useState<[Block[]]>([[]]);

  useEffect(() => {
    const chunkedBlocks = evenlyDistrubuteArrayOfArrays(blocks, numColumns);
    setSplitColumns(chunkedBlocks as [Block[]]);
  }, [blocks, numColumns]);
  return (
    <BlockColumnWrapper columnWidth={columnWidth} numColumns={numColumns}>
      {splitColumns.map((blocks, i) => {
        return (
          <InnerGrid key={'blocks' + i}>
            {blocks.map((block) => {
              return (
                <SelectableBlockSpacer key={block.src}>
                  <SelectableBlock
                    src={block.src}
                    isSelected={block.isSelected}
                    onBlockClick={onBlockClick}
                    width={columnWidth}
                  />
                </SelectableBlockSpacer>
              );
            })}
          </InnerGrid>
        );
      })}
      <InnerGrid />
    </BlockColumnWrapper>
  );
};

export default BlockColumnLayout;
