import * as React from "react";
import * as shortid from "shortid";
import OptionsWidget from "./OptionsWidget";
import { DragDropContext, Droppable } from "react-beautiful-dnd";
import { Question, InputProps, optionTypes } from "."
import * as AddIcon from "../../assets/img/add-icon.png";
import "./SignupQuestionsWidget.scss";
import TypeWidget from "./TypeWidget";
import QuestionList from "./QuestionList";

export interface SignupQuestionsWidgetProps {
  value: string;
  onChange: (value: string) => void;
  onFocus: () => void;
  required: boolean;
  disabled: boolean;
}
export interface SignupQuestionsWidgetState { }

class SignupQuestionsWidget extends React.Component<SignupQuestionsWidgetProps, SignupQuestionsWidgetState> {
  onValueChange = (questions: Question[]) => {
    const { onChange } = this.props;
    const newValue = JSON.stringify(questions);
    onChange(newValue);
  }

  handleNewRowClick = (questions) => () => {
    const newRow: Question = {
      id: shortid.generate(),
      name: `Question #${questions.length + 1}`,
      options: [],
      type: "text",
    };
    const newQuestions: Question[] = questions.concat([newRow]);

    this.onValueChange(newQuestions);
  }

  handleDragEnd = (questions: Question[]) => (result) => {
    const srcIndex = result.source.index;
    const dstIndex = result.destination.index;
    const srcCopy = { ...questions[srcIndex] };
    questions.splice(srcIndex, 1);
    questions.splice(dstIndex, 0, srcCopy);

    this.onValueChange(questions);
  }

  render() {
    const { value, onFocus } = this.props;

    const questions = JSON.parse(value) as Question[];

    return (
      <div className="signup-questions-widget">
        <DragDropContext
          onDragEnd={this.handleDragEnd(questions)}
          onDragStart={onFocus}
        >
          <Droppable droppableId="questions">
            {(provided) => (
              <QuestionList
                {...provided.droppableProps}
                innerRef={provided.innerRef}
                questions={questions}
                onChange={this.onValueChange}
                placeholder={provided.placeholder} />
            )}
          </Droppable>
        </DragDropContext>
        <button type="button" className="add-link" onClick={this.handleNewRowClick(questions)}>
          <img src={AddIcon} /> New Question
        </button>
      </div>
    );
  }
}

export default SignupQuestionsWidget;
