import classNames from 'classnames';
import React, { PropTypes } from 'react';
import update from 'immutability-helper';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import KdItemSelectedDraggable from '../KdItemSelectedDraggable';

const propTypes = {
  theme: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.func,
  ]).isRequired,
  items: PropTypes.array,
  updateItemPosition: PropTypes.func,
  toggleItemDirection: PropTypes.func,
  chicklets: PropTypes.shape({
    sortable: PropTypes.bool,
    visible: PropTypes.bool,
    fullwidth: PropTypes.bool,
    prefix: PropTypes.string,

    buttons: PropTypes.shape({
      ascDesc: PropTypes.shape({ visible: PropTypes.bool }),
      info: PropTypes.shape({ visible: PropTypes.bool }),
    }),

    events: PropTypes.shape({
      onClick: PropTypes.func,
      onClose: PropTypes.func,
    }),

    clearAll: PropTypes.shape({
      visible: PropTypes.bool,
      onClick: PropTypes.func,
    }),
  }),
};

@DragDropContext(HTML5Backend)
class KdChickletsContainerDraggable extends React.Component {

  constructor(props) {
    super(props);
    this.moveCard = this.moveCard.bind(this);
    this.state = { items: this.props.items };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.items !== this.state.items) {
      this.setState({ items: nextProps.items });
    }
  }

  moveCard(dragIndex, hoverIndex) {
    const { items } = this.state;
    const dragItem = items[dragIndex];
    this.setState(update(this.state, {
      items: {
        $splice: [
          [dragIndex, 1], [hoverIndex, 0, dragItem],
        ],
      },
    }));

    this.props.updateItemPosition(dragItem.value, hoverIndex);
  }

  render() {
    const { items } = this.state;
    const { theme } = this.props;
    return (
      <div className={
        classNames('c-kd-item-container-draggable', theme['c-kd-item-container-draggable'])
      }
      >
        {
          items.map((item, i) => (
            <KdItemSelectedDraggable
              theme={theme}
              index={i}
              moveCard={this.moveCard}
              updateItemPosition={this.props.updateItemPosition}
              toggleItemDirection={this.props.toggleItemDirection}
              chicklets={this.props.chicklets}
              {...item}
            />
          ))
        }
      </div>
    );
  }
}

KdChickletsContainerDraggable.propTypes = propTypes;

export default KdChickletsContainerDraggable;
