import React from "react";
import styled from "styled-components";
import Draggable from "@components/Draggable";
import colors from "@theme/colors";
import { SignupFormQuestion } from "@models/Signup";
import { Lang } from "../../../i18n";
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: SignupFormQuestion[];
  onChange: (value: SignupFormQuestion[]) => void;
}

const QuestionList: React.FC<QuestionListProps> = ({ questions, onChange }): JSX.Element => {
  const handleDrag = (srcIndex, dstIndex) => {
    const srcCopy = { ...questions[srcIndex] };
    questions.splice(srcIndex, 1);
    questions.splice(dstIndex, 0, srcCopy);
    onChange(questions);
  };

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

  const handleNameInputChange = (index: number, lang: Lang): React.ChangeEventHandler<HTMLInputElement> => (event) => {
    const val = event.target.value;
    if (lang === "fi") {
      // eslint-disable-next-line no-param-reassign
      questions[index].title_fi = val;
    }
    if (lang === "en") {
      // eslint-disable-next-line no-param-reassign
      questions[index].title_en = val;
    }
    onChange(questions);
  };

  return (
    <div data-e2e="admin-signup-question">
      {questions.map((q, index) => {
        const inputProps = {
          value: q.options,
          type: q.type,
          questions,
          index,
        };
        const optionsWidget = <OptionsWidget inputProps={inputProps} onChange={onChange} />;
        const typeSelectWidget = <TypeWidget inputProps={inputProps} onChange={onChange} />;
        return (
          <Draggable
            key={q.id}
            id={q.id}
            index={index}
            handleDrag={handleDrag}
          >
            <WidgetRow>
              <QuestionElement
                onClick={handleElementRemove(index)}
              >
                <input type="text" value={q.title_fi} onChange={handleNameInputChange(index, "fi")} />
                <input type="text" value={q.title_en} onChange={handleNameInputChange(index, "en")} />
                {typeSelectWidget}
                {optionsWidget}
              </QuestionElement>
            </WidgetRow>
          </Draggable>
        );
      })}
    </div>
  );
};

export default QuestionList;
