import React from "react";
import styled from "styled-components";
import shortid from "shortid";
import { DragDropContext, Droppable } from "react-beautiful-dnd";
import colors from "@theme/colors";
import AddIcon from "@components/AddIcon";
import QuestionList from "./QuestionList";
import { Question } from "./common";

const Widget = styled.div`
  & > button {
    display: flex;
    flex-flow: row nowrap;
    align-items: center;

    background: none;
    padding: 0;
    margin: 1rem 0;

    & > div {
      margin-right: 8px !important;
      margin-top: -2px !important;
    }

  }
`;

const AddQuestionButton = styled.button`
  background-color: ${colors.blue1};
  color: ${colors.white};
  border: none;
  outline: none;
  cursor: pointer;
`;

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

const SignupQuestionsWidget: React.FC<SignupQuestionsWidgetProps> = ({ value, onFocus, onChange }) => {
  const onValueChange = (questions: Question[]) => {
    const newValue = JSON.stringify(questions);
    onChange(newValue);
  };

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

    onValueChange(newQuestions);
  };

  const 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);

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

  return (
    <Widget>
      <DragDropContext
        onDragEnd={handleDragEnd(questions)}
        onDragStart={onFocus}
      >
        <Droppable droppableId="questions">
          {(provided) => (
            <QuestionList
              {...provided.droppableProps}
              innerRef={provided.innerRef}
              questions={questions}
              onChange={onValueChange}
              placeholder={provided.placeholder}
            />
          )}
        </Droppable>
      </DragDropContext>
      <AddQuestionButton type="button" onClick={handleNewRowClick(questions)} data-e2e="admin-signup-new-question">
        <AddIcon />
        New Question
      </AddQuestionButton>
    </Widget>
  );
};

export default SignupQuestionsWidget;
