import React from "react";
import styled from "styled-components";
import shortid from "shortid";
import colors from "@theme/colors";
import AddIcon from "@components/AddIcon";
import { SignupFormQuestion } from "@models/Signup";
import QuestionList from "./QuestionList";

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;
}

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

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

    onValueChange(newQuestions);
  };

  const questions: SignupFormQuestion[] = JSON.parse(value);

  return (
    <Widget>
      <QuestionList
        questions={questions}
        onChange={onValueChange}
      />
      <AddQuestionButton type="button" onClick={handleNewRowClick(questions)} data-e2e="admin-signup-new-question">
        <AddIcon />
        New Question
      </AddQuestionButton>
    </Widget>
  );
};

export default SignupQuestionsWidget;
