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

function ProblemsPage(): JSX.Element {
  const question = "problems";
  const stepId = "profile";
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { translate } = useTranslations(ELocalesPlacement.V1);
  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);
  const { width: pageWidth, elementRef: pageRef } = useDynamicSize({});
  const [selectedAnswer, setSelectedAnswer] = useState<IAnswer | null>(null);
  const clickAnswerTimeOutRef = useRef<NodeJS.Timeout>();

  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(
        translate("/problems.title_partner", {
          gender: translate(gender?.toLowerCase()),
          age: getAge(questionsAnswers.birthdate),
          parent:
            questionsAnswers.parent === "yes"
              ? translate("/problems.title_parent")
              : "",
        }) as string
      );
    }
    if (["single", "complicated", "other"].includes(flowChoice)) {
      return setQuestionTitle(
        translate("/problems.title_self", {
          gender: translate(gender?.toLowerCase()),
          age: getAge(questionsAnswers.birthdate),
          parent:
            questionsAnswers.parent === "yes"
              ? translate("/problems.title_parent")
              : "",
        }) as string
      );
    }
  }, [
    questionsAnswers.birthdate,
    questionsAnswers.flowChoice,
    gender,
    questionsAnswers.parent,
    translate,
  ]);

  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.genderV1());
    setCurrentQuestion(_currentQuestion);
  }, [navigate, question, stepId, steps]);

  const answerClickHandler = async (answer: IAnswer) => {
    if (!stepId || !question) return;
    const questionIndex = getIndexOfQuestion(question);
    if (questionIndex === -1) return;

    setSelectedAnswer(answer);
    await new Promise(
      (resolve) => (clickAnswerTimeOutRef.current = setTimeout(resolve, 400))
    );

    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,
      })
    );
    setSelectedAnswer(null);

    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.questionnaireV1()}/${steps[currentStepIndex].id}/${
          steps[currentStepIndex].questions[questionIndex + 1].id
        }`
      );
    }

    if (
      currentStepIndex < steps.length - 1 &&
      questionIndex >= questionsLength - 1
    ) {
      return navigate(
        `${routes.client.questionnaireV1()}/${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 || ""})`,
        backgroundColor:
          questionsAnswers.gender === "male" ? "#C1E5FF" : "#f7ebff",
      }}
      ref={pageRef}
    >
      <Header className={styles.header} />
      <BackgroundTopBlob
        width={pageWidth}
        height={214}
        className={styles["background-top-blob"]}
      />
      {currentQuestion && (!!currentStep || currentStep === 0) && (
        <>
          <div className={styles["stepper-container"]}>
            <Stepper
              steps={steps}
              currentStep={currentStep}
              currentQuestion={getIndexOfQuestion(currentQuestion.id)}
            />
          </div>
          <span
            className={styles["current-step"]}
            style={{
              color: steps[currentStep].color,
            }}
          >
            {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}
                    classNameContainer={`${
                      selectedAnswer?.id === answer.id
                        ? styles["answer-active"]
                        : ""
                    } ${styles["answer"]}`}
                    onClick={() => {
                      answerClickHandler(answer);
                    }}
                  />
                );
              })}
            {!!currentQuestion.answersElement && currentQuestion.answersElement}
          </div>
        </>
      )}
    </section>
  );
}

export default ProblemsPage;
