import React from 'react';
import { Page } from '../Page';
import { BoardCard } from './BoardCard';
import { connect } from 'react-redux';
import { fetchBoards } from '../../store/actions/boards';
import { fetchProjects } from '../../store/actions/projects';
import { selectBoardByUserProjects } from '../../store/selectors/boards';

export class HomePage extends React.Component {
  render() {
    return (
      <Page title="GenGitKan - Accueil">
        <div className="container is-fluid">
          <div className="level has-margin-top-normal">
            <div className="level-left"></div>
            <div className="level-right">
              <div className="buttons">
                <a className="button is-primary" href="#/boards/new">
                  <span className="icon">
                    <i className="fas fa-plus"></i>
                  </span>
                  <span>Nouveau tableau</span>
                </a>
              </div>
            </div>
          </div>
          { this.renderBoards() }
        </div>
      </Page>
    );
  }

  renderBoards() {
    const { boards } = this.props;
    const rows = Object.values(boards)
      .reduce((boardRows, board, index) => {
        if (index % 3 === 0) {
          boardRows.push([]);
        }
        boardRows[boardRows.length-1].push(board);
        return boardRows;
      }, [])
      .map((row, rowIndex) => {
        const tiles = row.map((board) => {
          return (
            <div key={`board-${board.id}`} className={`tile is-parent is-4`}>
              <div className="tile is-child">
                <BoardCard board={board} />
              </div>
            </div>
          );
        });
        return (
          <div key={`boards-row-${rowIndex}`} className="tile">
            {tiles}
          </div>
        );
      });
    ;

    return (
      <div className="tile is-ancestor is-vertical">
        { rows }
      </div>
    );
  }

  componentDidMount() {
    this.props.dispatch(fetchBoards());
    this.props.dispatch(fetchProjects());
  }

}

export const ConnectedHomePage = connect(function(state) {
  return {
    boards: selectBoardByUserProjects(state.boards.byID, state.projects.byName)
  };
})(HomePage);