import React, { ReactNode } from "react";
import styled from "styled-components";
import { Draggable } from "react-beautiful-dnd";
import { colors } from "@theme/colors";
import { Question, InputProps } from "./common";
import OptionsWidget from "./OptionsWidget";
import TypeWidget from "./TypeWidget";
import QuestionElement from "./Question";

const WidgetRow = styled.div`
  margin-bottom: 1rem;
  display: flex;
  flex-flow: column nowrap;
  padding: 0.5rem;
  background-color: ${colors.lightBlue};
`;

interface QuestionListProps {
  questions: Question[];
  innerRef: React.Ref<HTMLDivElement>;
  placeholder: ReactNode;
  onChange: (value: Question[]) => void;
}

class QuestionList extends React.Component<QuestionListProps> {
  renderTextWidget = ({ questions, value, index }: InputProps) => (
    <input type="text" value={value} onChange={this.handleNameInputChange(questions, index)} />
  );

  handleNameInputChange = (questions: Question[], index: number) => (event) => {
    const { onChange } = this.props;
    const val = event.target.value;
    // eslint-disable-next-line no-param-reassign
    questions[index].name = val;
    onChange(questions);
  };

  handleElementRemove = (questions: Question[], index: number) => () => {
    const { onChange } = this.props;
    const newQuestions = [...questions];
    newQuestions.splice(index, 1);
    onChange(newQuestions);
  };

  renderQuestions() {
    const { questions, onChange } = this.props;
    return questions.map((q, index) => {
      const nameWidgetProps = {
        value: q.name, type: "text", questions, index,
      };
      const nameWidget = this.renderTextWidget(nameWidgetProps);

      const dataProps = {
        value: q.options, type: q.type, questions, index,
      };
      const optionsWidget = <OptionsWidget inputProps={dataProps} onChange={onChange} />;
      const typeSelectWidget = <TypeWidget inputProps={dataProps} onChange={onChange} />;
      return (
        <Draggable draggableId={q.id} key={q.id} index={index}>
          {(provided) => (
            <WidgetRow
              {...provided.draggableProps}
              {...provided.dragHandleProps}
              ref={provided.innerRef}
            >
              <QuestionElement
                onClick={this.handleElementRemove(questions, index)}
              >
                {nameWidget}
                {typeSelectWidget}
                {optionsWidget}
              </QuestionElement>
            </WidgetRow>
          )}
        </Draggable>
      );
    });
  }

  render() {
    const { placeholder, innerRef } = this.props;

    return (
      <div ref={innerRef} data-e2e="admin-signup-question">
        {this.renderQuestions()}
        {placeholder}
      </div>
    );
  }
}

export default QuestionList;
