import { Box, Link, useTheme } from "@mui/material";

import { Footer } from "./Footer";
import { Date } from "./questions/Date";
import { Emoji } from "./questions/Emoji";
import { File } from "./questions/File";
import { Images } from "./questions/Images";
import { Number } from "./questions/Number";
import { Page } from "./questions/Page";
import { Rating } from "./questions/Rating";
import { Select } from "./questions/Select";
import { Text } from "./questions/Text";
import { Variant } from "./questions/Variant";
import { Varimg } from "./questions/Varimg";

import type { RealTypedQuizQuestion } from "../../model/questionTypes/shared";

import { NameplateLogoFQ } from "@icons/NameplateLogoFQ";
import { NameplateLogoFQDark } from "@icons/NameplateLogoFQDark";
import { notReachable } from "@utils/notReachable";
import { quizThemes } from "@utils/themes/Publication/themePublication";

import { DESIGN_LIST } from "@/utils/designList";
import { type ReactNode } from "react";
import { isProduction } from "@/utils/defineDomain";
import { useQuizStore } from "@/stores/useQuizStore";
import { CustomCircularTimer } from "@/ui_kit/timer/CircularTimer";
import { useQuestionTimer } from "@/utils/hooks/FlowControlLogic/useQuestionTimer";
import { useState, useEffect } from "react";

type Props = {
  currentQuestion: RealTypedQuizQuestion;
  currentQuestionStepNumber: number | null;
  nextButton: ReactNode;
  prevButton: ReactNode;
  questionSelect: ReactNode;
};

export const Question = ({
  currentQuestion,
  currentQuestionStepNumber,
  nextButton,
  prevButton,
  questionSelect,
}: Props) => {
  const theme = useTheme();
  const { settings, show_badge, quizId, preview } = useQuizStore();

  // Состояние для отслеживания оставшегося времени
  const [remainingTime, setRemainingTime] = useState<number>(0);
  const [isTimerActive, setIsTimerActive] = useState<boolean>(false);

  // Получаем настройки таймера
  const timerEnabled = Boolean(settings.questionTimerEnabled);
  const timerDuration = settings.cfg.time_of_passing ?? 0;

  // Эффект для обновления таймера
  useEffect(() => {
    if (timerEnabled && timerDuration > 0) {
      setRemainingTime(timerDuration);
      setIsTimerActive(true);

      const interval = setInterval(() => {
        setRemainingTime((prev) => {
          if (prev <= 1) {
            setIsTimerActive(false);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);

      return () => clearInterval(interval);
    } else {
      setIsTimerActive(false);
      setRemainingTime(0);
    }
  }, [timerEnabled, timerDuration, currentQuestion.id]);

  return (
    <Box
      sx={{
        height: "100%",
        backgroundPosition: "center",
        backgroundSize: "cover",
        backgroundImage: settings.cfg.design ? `url(${DESIGN_LIST[settings.cfg.theme]})` : null,
      }}
    >
      <Box
        sx={{
          height: "100%",
          display: "flex",
          flexDirection: "column",
          background: settings.cfg.design
            ? quizThemes[settings.cfg.theme].isLight
              ? "transparent"
              : "linear-gradient(90deg,#272626, transparent)"
            : theme.palette.background.default,
          overflow: "hidden",
        }}
      >
        <Box
          sx={{
            overflow: "auto",
            width: "100%",
            flexGrow: 1,
            scrollbarWidth: "none",
            "&::-webkit-scrollbar": {
              width: 0,
            },
          }}
        >
          <Box
            sx={{
              width: "100%",
              minHeight: "100%",
              maxWidth: "1440px",
              padding: "40px 25px 20px",
              margin: "0 auto",
              display: "flex",
              flexDirection: "column",
              justifyContent: "space-between",
            }}
          >
            <QuestionByType
              key={currentQuestion.id}
              question={currentQuestion}
              stepNumber={currentQuestionStepNumber}
            />
            <Box
              sx={{
                mt: "20px",
                alignSelf: "end",
                display: "flex",
                flexDirection: "column",
                alignItems: "end",
                gap: "13px",
              }}
            >
              {timerEnabled && isTimerActive && (
                <CustomCircularTimer
                  duration={timerDuration}
                  remaining={remainingTime}
                  showTime={true}
                  size={76}
                  thickness={4}
                />
              )}
              {show_badge && (
                <Link
                  target="_blank"
                  href={`https://${isProduction ? "" : "s"}quiz.pena.digital/answer/v1.0.0/logo?q=${quizId}`}
                >
                  {quizThemes[settings.cfg.theme].isLight ? (
                    <NameplateLogoFQ
                      style={{
                        fontSize: "34px",
                        width: "200px",
                        height: "auto",
                      }}
                    />
                  ) : (
                    <NameplateLogoFQDark
                      style={{
                        fontSize: "34px",
                        width: "200px",
                        height: "auto",
                      }}
                    />
                  )}
                </Link>
              )}
            </Box>
          </Box>
        </Box>
        {questionSelect}
        <Footer
          stepNumber={currentQuestionStepNumber}
          prevButton={prevButton}
          nextButton={nextButton}
        />
      </Box>
    </Box>
  );
};

function QuestionByType({ question, stepNumber }: { question: RealTypedQuizQuestion; stepNumber: number | null }) {
  switch (question.type) {
    case "variant":
      return <Variant currentQuestion={question} />;
    case "images":
      return <Images currentQuestion={question} />;
    case "varimg":
      return <Varimg currentQuestion={question} />;
    case "emoji":
      return <Emoji currentQuestion={question} />;
    case "text":
      return (
        <Text
          currentQuestion={question}
          stepNumber={stepNumber}
        />
      );
    case "select":
      return <Select currentQuestion={question} />;
    case "date":
      return <Date currentQuestion={question} />;
    case "number":
      return <Number currentQuestion={question} />;
    case "file":
      return <File currentQuestion={question} />;
    case "page":
      return <Page currentQuestion={question} />;
    case "rating":
      return <Rating currentQuestion={question} />;
    default:
      notReachable(question);
  }
}
