import React, { Component } from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
import { connect } from 'react-redux';
import {
  addNewPage,
  setActivePage,
  deletePage,
  switchFormPage,
  updateActiveView,
} from '../../redux/action-creators/form-builder-actions/form-builder.actions';
import {
  FormPageButton,
  TabButton,
} from '../../components/common/buttons/IconButton';

const reorder = (list, startIndex, endIndex) => {
  const result = Array.from(list);
  const [removed] = result.splice(startIndex, 1);
  result.splice(endIndex, 0, removed);
  return result;
};

class FormPageTabs extends Component {
  onDragEnd = result => {
    const tempPages = [...this.props.formData];
    // dropped outside the list
    if (!result.destination) {
      return;
    }

    const items = reorder(
      tempPages,
      result.source.index,
      result.destination.index
    );

    const updatedPages = [];
    items.forEach((page, i) => {
      updatedPages.push({
        ...page,
        label: `Page ${i + 1}`,
        pos: `${i + 1}`,
      });
    });
    this.props.switchFormPage(updatedPages);
  };

  onDeletePage = index => {
    const { formData, activePage, deletePage, updateActiveView } = this.props;
    const tempDeletePage = [...formData];
    const filteredPage = [];
    if (formData.length > 1) {
      tempDeletePage.forEach((page, i) => {
        if (i !== index) {
          filteredPage.push({
            ...page,
            label: `Page ${i + 1}`,
            pos: `${i + 1}`,
          });
        }
        if (i === index && page.label === activePage) {
          setActivePage(0);
          [...formData].forEach(page => {
            if (page.label === activePage) {
              updateActiveView(page);
            }
          });
        }
      });
      deletePage(filteredPage);
    }
  };

  onAddNewPage = () => {
    const { addNewPage, formData } = this.props;
    const newPage = [...formData];
    newPage.push({
      label: `Page ${newPage.length + 1}`,
      pos: newPage.length + 1,
      elements: [],
    });
    addNewPage(newPage);
  };

  onSetActivePage = index => {
    const { setActivePage, formData, updateActiveView } = this.props;
    setActivePage(index);
    [...formData].forEach(page => {
      if (`Page ${index + 1}` === page.label) {
        updateActiveView(page);
      }
    });
  };

  render() {
    const { formData, activePage } = this.props;
    return (
      <div>
        <DragDropContext onDragEnd={this.onDragEnd}>
          <Droppable droppableId="droppable" direction="horizontal">
            {provided => (
              <div className="d-flx-alc">
                <div
                  className="float-child-wrap page-extras "
                  style={{ overflow: 'auto' }}
                  {...provided.droppableProps}
                  ref={provided.innerRef}
                >
                  {formData.map((item, index) => {
                    return (
                      <Draggable
                        key={`key${index}`}
                        draggableId={`formpage${index}`}
                        index={index}
                      >
                        {provided => (
                          <div
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                            {...provided.dragHandleProps}
                          >
                            <FormPageButton
                              title={`Page ${index + 1}`}
                              onclickPage={() => this.onSetActivePage(index)}
                              onclickDelete={() => this.onDeletePage(index)}
                              svg="cancel"
                              className={
                                item.label === activePage ? 'active' : ''
                              }
                            />
                          </div>
                        )}
                      </Draggable>
                    );
                  })}
                  {provided.placeholder}
                </div>
                <span onClick={() => this.onAddNewPage()}>
                  <TabButton title="Add" svg="plus-round-bg" />
                </span>
              </div>
            )}
          </Droppable>
        </DragDropContext>
      </div>
    );
  }
}

export default connect(null, {
  addNewPage,
  setActivePage,
  deletePage,
  switchFormPage,
  updateActiveView,
})(FormPageTabs);
