import { Box, Button, useMediaQuery, useTheme } from "@mui/material";
import CreationCard from "@ui_kit/CreationCard";
import quizCreationImage1 from "@/assets/quiz-creation-1.png";
import quizCreationImage2 from "@/assets/quiz-creation-2.png";
import { setQuizType, updateQuiz } from "@root/quizes/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { useEffect, useRef, useState } from "react";

import arrowLeftIcon from "@/assets/icons/arrow_left.svg";
import arrowRightIcon from "@/assets/icons/arrow_right.svg";
import QuizgenegationName from "@utils/quizgenegationName";
import { QuizType } from "@model/quizSettings";

export default function StepOne() {
  const quiz = useCurrentQuiz();
  const config = quiz?.config;
  const theme = useTheme();
  const isSlider = useMediaQuery(theme.breakpoints.down(950));

  const containerRef = useRef<HTMLDivElement | null>(null);
  const buttonRefs = useRef<(HTMLButtonElement | null)[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    if (containerRef.current && buttonRefs.current.length > 0) {
      const buttonWidth = buttonRefs.current[0]!.offsetWidth;

      containerRef.current.scrollTo({
        left: currentIndex * buttonWidth,
        behavior: "smooth",
      });
    }
  }, [currentIndex]);

  const handlePrevClick = () => {
    setCurrentIndex((prevIndex) => Math.max(prevIndex - 1, 0));
  };

  const handleNextClick = () => {
    setCurrentIndex((prevIndex) => Math.min(prevIndex + 1, 1));
  };

  const handleTypeClick = (typeQuiz: QuizType) => {
    setQuizType(quiz.id, typeQuiz);
    if (
      quiz.name === "" ||
      quiz.name === " " ||
      quiz.name ===
        "No type " + quiz.backendId.toString().slice(-4).replace(/^0/, "1")
    ) {
      updateQuiz(quiz.id, (quiz) => {
        quiz.name = QuizgenegationName({ quiz });
      });
    }
  };

  if (!config) return null;

  return (
    <Box
      sx={{
        overflowX: "scroll",
        padding: "0 5px 15px",
        "&::-webkit-scrollbar": { width: 0 },
      }}
    >
      <Box
        ref={containerRef}
        sx={{
          overflow: "auto",
          display: "flex",
          gap: "20px",
          mt: "60px",
          position: "relative",
          scrollbarWidth: "none",
          "&::-webkit-scrollbar": {
            width: 0,
          },
        }}
      >
        <Button
          sx={{ minWidth: "325px" }}
          ref={(ref) => (buttonRefs.current[0] = ref as HTMLButtonElement)}
          variant="text"
          data-cy="create-quiz-card"
          onClick={() => {
            handleTypeClick("quiz");
          }}
        >
          <CreationCard
            header="Создание quiz-опроса"
            text="Стартовая страница - это ваша визитка, от качества её будет зависеть, как конверсия пользователей которые захотели пройти ваш опрос, так и конверсия в форму контактных данных, так как именно стартовая страница - залог доверия клиентов к вам"
            image={quizCreationImage1}
            border={config.type === "quiz" ? "1px solid #7E2AEA" : "none"}
          />
        </Button>
        <Button
          sx={{ minWidth: "325px" }}
          ref={(ref) => (buttonRefs.current[1] = ref as HTMLButtonElement)}
          variant="text"
          onClick={() => {
            handleTypeClick("form");
          }}
        >
          <CreationCard
            header="Создание анкеты"
            text="Режим анкеты создан, в целях оставить пользователю варианты вопросов используемых в исследованиях и убирания всего лишнего, что может мешать и приводить к ошибкам"
            image={quizCreationImage2}
            border={config.type === "form" ? "1px solid #7E2AEA" : "none"}
          />
        </Button>
      </Box>

      {isSlider && (
        <>
          <img
            onClick={handlePrevClick}
            style={{
              position: "absolute",
              left: "0",
              top: "50%",
              width: "40px",
              height: "40px",
            }}
            src={arrowLeftIcon}
          />
          <img
            onClick={handleNextClick}
            style={{
              position: "absolute",
              right: "0",
              top: "50%",
              width: "40px",
              height: "40px",
            }}
            src={arrowRightIcon}
          />
        </>
      )}
    </Box>
  );
}
