import { useNavigate } from "react-router-dom";
import styles from "./styles.module.css";
import Stepper from "@/components/Stepper";
import { useEffect, useState } from "react";
import { IAnswer, IQuestion, relationshipAnswers, singleAnswers, stepsQuestionary } from "@/data";
import Title from "@/components/Title";
import Answer from "@/components/Answer";
import routes from "@/routes";
import { useDispatch, useSelector } from "react-redux";
import { actions } from "@/store";
import { selectQuestionnaire } from "@/store/questionnaire";
import { getAge } from "@/services/date";

function ProblemsPage(): JSX.Element {
  const question = "problems";
  const stepId = "profile";
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [currentStep, setCurrentStep] = useState<number>();
  const [currentQuestion, setCurrentQuestion] = useState<IQuestion>();
  const steps = stepsQuestionary.filter((item) => !!item.questions.length);
  const [questionTitle, setQuestionTitle] = useState("");
  const [answers, setAnswers] = useState<IAnswer[]>([]);
  const questionsAnswers = useSelector(selectQuestionnaire);
  const gender =
    questionsAnswers.gender[0].toUpperCase() + questionsAnswers.gender.slice(1);

  useEffect(() => {
    const flowChoice = questionsAnswers.flowChoice;
    if (["relationship", "married"].includes(flowChoice)) {
      return setAnswers(relationshipAnswers);
    }
    if (["single", "complicated", "other"].includes(flowChoice)) {
      return setAnswers(singleAnswers);
    }
  }, [questionsAnswers.flowChoice]);

  useEffect(() => {
    const flowChoice = questionsAnswers.flowChoice;
    if (["relationship", "married"].includes(flowChoice)) {
      return setQuestionTitle(
        `${gender} in their ${getAge(questionsAnswers.birthdate)}s ${
          questionsAnswers.parent === "yes" && "who have children"
        } need a slightly different approach to improve their relationship. Which statement best describes you?`
      );
    }
    if (["single", "complicated", "other"].includes(flowChoice)) {
      return setQuestionTitle(
        `Single ${gender} in their ${getAge(questionsAnswers.birthdate)}s ${
          questionsAnswers.parent === "yes" && "who have children"
        } need a slightly different approach to find their perfect partner. But first, how did you feel in your last relationship?`
      );
    }
  }, [
    questionsAnswers.birthdate,
    questionsAnswers.flowChoice,
    gender,
    questionsAnswers.parent,
  ]);

  useEffect(() => {
    const currentStepIndex = steps.findIndex((item) => item.id === stepId);
    if (currentStepIndex === -1) return navigate(routes.client.notFound());
    setCurrentStep(currentStepIndex || 0);
    const _currentQuestion = steps[currentStepIndex].questions.find(
      (item) => item.id === question
    );
    if (!_currentQuestion) return navigate(routes.client.gender());
    setCurrentQuestion(_currentQuestion);
  }, [navigate, question, stepId, steps]);

  const answerClickHandler = (answer: IAnswer) => {
    if (!stepId || !question) return;
    const questionIndex = getIndexOfQuestion(question);
    if (questionIndex === -1) return;
    const currentStepIndex = steps.findIndex((item) => item.id === stepId);

    const questionsLength = steps[currentStepIndex].questions.length;

    const currentQuestion = steps[currentStepIndex].questions[questionIndex];

    dispatch(
      actions.questionnaire.update({
        [currentQuestion.id]: answer.id,
      })
    );

    if (answer.navigateToUrl?.length) {
      return navigate(answer.navigateToUrl);
    }

    if (currentQuestion.navigateToUrl?.length) {
      return navigate(currentQuestion.navigateToUrl);
    }

    if (
      currentStepIndex >= steps.length - 1 &&
      questionIndex >= questionsLength - 1
    ) {
      return navigate(routes.client.priceList());
    }

    if (questionIndex < questionsLength - 1) {
      return navigate(
        `${routes.client.questionnaire()}/${steps[currentStepIndex].id}/${
          steps[currentStepIndex].questions[questionIndex + 1].id
        }`
      );
    }

    if (
      currentStepIndex < steps.length - 1 &&
      questionIndex >= questionsLength - 1
    ) {
      return navigate(
        `${routes.client.questionnaire()}/${steps[currentStepIndex + 1].id}/${
          steps[currentStepIndex + 1].questions[0].id
        }`
      );
    }
  };

  const getIndexOfQuestion = (questionId: string) => {
    const currentStepIndex = steps.findIndex((item) => item.id === stepId);
    if (currentStepIndex === -1) return -1;
    return steps[currentStepIndex].questions.findIndex(
      (item) => item.id === questionId
    );
  };

  return (
    <section
      className={`${styles.page} page`}
      style={{
        backgroundImage: `url(${currentQuestion?.backgroundImage || ""})`,
      }}
    >
      {currentQuestion && (!!currentStep || currentStep === 0) && (
        <>
          <Stepper
            steps={steps}
            currentStep={currentStep}
            currentQuestion={getIndexOfQuestion(currentQuestion.id)}
          />
          <span className={styles["current-step"]}>
            {steps[currentStep].label}
          </span>
          <Title className={styles.title} variant="h1">
            {questionTitle}
          </Title>
          {!!currentQuestion.description && (
            <p className={styles.description}>{currentQuestion.description}</p>
          )}
          <div className={styles["answers-container"]}>
            {!currentQuestion.answersElement &&
              (currentQuestion.answers?.length
                ? currentQuestion.answers
                : answers
              ).map((answer) => {
                // if (!isShowAnswer(answer)) return null;
                return (
                  <Answer
                    key={answer.id}
                    answer={answer}
                    onClick={() => {
                      answerClickHandler(answer);
                    }}
                  />
                );
              })}
            {!!currentQuestion.answersElement && currentQuestion.answersElement}
          </div>
        </>
      )}
    </section>
  );
}

export default ProblemsPage;
