import React from 'react';
import { Page } from '../Page';
import { connect } from 'react-redux';
import Board from '@lourenci/react-kanban';
import { fetchIssues } from '../../store/actions/issues';
import { fetchBoards } from '../../store/actions/boards';
import { buildKanboard, moveCard } from '../../store/actions/kanboards';
import { Loader } from '../Loader';

export class BoardPage extends React.Component {

  render() {
    return (
      <Page>
        <div className="container is-fluid">
          {this.renderBoard()}
        </div>
      </Page>
    );
  }

  renderBoard() {
    const { kanboard } = this.props;
    
    if (!kanboard) {
      return <Loader></Loader>
    }

    return (
      <div className="kanboard-container is-fullheight">
        <Board disableLaneDrag={true}
          renderCard={this.renderCard}
          renderLaneHeader={this.renderLaneHeader}
          onCardDragEnd={this.onCardDragEnd.bind(this)}>
          {kanboard}
        </Board>
      </div>
    );
  }

  renderCard(card) {
    return (
      <div className="kanboard-card">
        <div className="box">
          <div className="media">
            <div className="media-content">
              <div className="content">
                <h5 className="is-size-5 is-marginless">{card.title}</h5>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  renderLaneHeader(lane) {
    return (
      <h3 className="kanboard-lane-title is-size-3">{lane.title}</h3>
    )
  }

  onCardDragEnd(source, dest) {
    const { board } = this.props;
    this.props.dispatch(moveCard(
      board.id,
      source.fromLaneId,
      source.fromPosition,
      dest.toLaneId,
      dest.toPosition
    ));
  }

  componentDidMount() {
    const { board } = this.props;
    if (!board) {
      this.requestBoardsUpdate();
      return
    }

    this.requestBuildKanboard();
  }

  componentDidUpdate(prevProps) {
    if (prevProps.board !== this.props.board) this.requestBuildKanboard();
  }

  requestBoardsUpdate() {
    this.props.dispatch(fetchBoards());
  }

  requestBuildKanboard() {
    const { board } = this.props;
    if (!board) return;
    this.props.dispatch(buildKanboard(board));
  }

}

export const ConnectedBoardPage = connect(function(state, props) {
  const boardID = props.match.params.id;
  return {
    board: state.boards.byID[boardID],
    kanboard: state.kanboards.byID[boardID]
  };
})(BoardPage);