import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { useEventListener } from '../../../hooks/useEventListener';
import { DynamicText } from '../../typography/DynamicText';

export interface IQuestionDialogAnswer {
  id: number;
  text: string;
  nextQuestionId?: number;
}

export interface IQuestionDialog {
  id: number;
  text: string;
  answerIds?: number[];
}

export interface IProps {
  questions: IQuestionDialog[];
  answers: IQuestionDialogAnswer[];
  onClose: () => void;
}

export const QuestionDialog: React.FC<IProps> = ({
  questions,
  answers,
  onClose,
}) => {
  const [currentQuestion, setCurrentQuestion] = useState(questions[0]);

  const [canShowAnswers, setCanShowAnswers] = useState<boolean>(false);

  const onGetFirstAnswer = () => {
    if (!currentQuestion.answerIds || currentQuestion.answerIds.length === 0) {
      return null;
    }

    const firstAnswerId = currentQuestion.answerIds![0];

    return answers.find(answer => answer.id === firstAnswerId);
  };

  const [
    currentAnswer,
    setCurrentAnswer,
  ] = useState<IQuestionDialogAnswer | null>(onGetFirstAnswer()!);

  useEffect(() => {
    setCurrentAnswer(onGetFirstAnswer()!);
  }, [currentQuestion]);

  const onGetAnswers = (answerIds: number[]) => {
    return answerIds.map((answerId: number) =>
      answers.find(answer => answer.id === answerId)
    );
  };

  const onKeyPress = (e: KeyboardEvent) => {
    switch (e.key) {
      case 'ArrowDown':
        // select next answer, if any.
        // if no next answer, select first answer
        // const nextAnswer = onGetAnswers(currentQuestion.answerIds!).find(
        //   (answer) => answer?.id === currentAnswer!.id + 1
        // );

        const nextAnswerIndex = onGetAnswers(
          currentQuestion.answerIds!
        ).findIndex(answer => answer?.id === currentAnswer!.id + 1);

        const nextAnswerID = currentQuestion.answerIds![nextAnswerIndex];

        const nextAnswer = onGetAnswers(currentQuestion.answerIds!).find(
          answer => answer?.id === nextAnswerID
        );

        setCurrentAnswer(nextAnswer || onGetFirstAnswer()!);

        break;
      case 'ArrowUp':
        // select previous answer, if any.
        // if no previous answer, select last answer

        const previousAnswerIndex = onGetAnswers(
          currentQuestion.answerIds!
        ).findIndex(answer => answer?.id === currentAnswer!.id - 1);

        const previousAnswerID =
          currentQuestion.answerIds &&
          currentQuestion.answerIds[previousAnswerIndex];

        const previousAnswer = onGetAnswers(currentQuestion.answerIds!).find(
          answer => answer?.id === previousAnswerID
        );

        if (previousAnswer) {
          setCurrentAnswer(previousAnswer);
        } else {
          setCurrentAnswer(onGetAnswers(currentQuestion.answerIds!).pop()!);
        }

        break;
      case 'Enter':
        setCanShowAnswers(false);

        if (!currentAnswer?.nextQuestionId) {
          onClose();
          return;
        } else {
          setCurrentQuestion(
            questions.find(
              question => question.id === currentAnswer!.nextQuestionId
            )!
          );
        }

        break;
    }
  };
  useEventListener('keydown', onKeyPress);

  const onAnswerClick = (answer: IQuestionDialogAnswer) => {
    setCanShowAnswers(false);
    if (answer.nextQuestionId) {
      // if there is a next question, go to it
      setCurrentQuestion(
        questions.find(question => question.id === answer.nextQuestionId)!
      );
    } else {
      // else, finish dialog!
      onClose();
    }
  };

  const onRenderCurrentAnswers = () => {
    const answerIds = currentQuestion.answerIds;
    if (!answerIds) {
      return null;
    }

    const answers = onGetAnswers(answerIds);

    if (!answers) {
      return null;
    }

    return answers.map(answer => {
      const isSelected = currentAnswer?.id === answer?.id;
      const selectedColor = isSelected ? 'yellow' : 'white';

      if (answer) {
        return (
          <AnswerRow key={`answer_${answer.id}`}>
            <AnswerSelectedIcon color={selectedColor}>
              {isSelected ? 'X' : null}
            </AnswerSelectedIcon>

            <Answer
              key={answer.id}
              onPointerDown={() => onAnswerClick(answer)}
              color={selectedColor}
            >
              {answer.text}
            </Answer>
          </AnswerRow>
        );
      }

      return null;
    });
  };

  return (
    <Container>
      <QuestionContainer>
        <DynamicText
          text={currentQuestion.text}
          onStart={() => setCanShowAnswers(false)}
          onFinish={() => setCanShowAnswers(true)}
        />
      </QuestionContainer>

      {canShowAnswers && (
        <AnswersContainer>{onRenderCurrentAnswers()}</AnswersContainer>
      )}
    </Container>
  );
};

const Container = styled.div`
  display: flex;
  word-break: break-all;
  box-sizing: border-box;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
`;

const QuestionContainer = styled.div`
  flex: 100%;
  width: 100%;
`;

const AnswersContainer = styled.div`
  flex: 100%;
`;

interface IAnswerProps {
  color: string;
}

const Answer = styled.p<IAnswerProps>`
  flex: auto;
  color: ${props => props.color} !important;
  font-size: 0.65rem !important;
  background: inherit;
  border: none;
`;

const AnswerSelectedIcon = styled.span<IAnswerProps>`
  flex: 5% 0 0;
  color: ${props => props.color} !important;
`;

const AnswerRow = styled.div`
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  margin-bottom: 0.5rem;
  height: 22px;
  p {
    line-height: unset;
    margin-top: 0;
    margin-bottom: 0rem;
  }
`;
