import { quizApi } from "@api/quiz";
import { Box, useMediaQuery, useTheme, Skeleton } from "@mui/material";
import { setQuizes, setCurrentStep } from "@root/quizes/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { useQuizStore } from "@root/quizes/store";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { cleanQuestions, setQuestions } from "@root/questions/actions";
import {
  updateModalInfoWhyCantCreate,
  setShowConfirmLeaveModal,
  updateSomeWorkBackend,
} from "@root/uiTools/actions";
import { questionApi } from "@api/question";
import { useUiTools } from "@root/uiTools/store";

import { ConfirmLeaveModal } from "../startPage/ConfirmLeaveModal";
import { DesignFilling } from "./DesignFilling";
import { createPortal } from "react-dom";
import QuizPreview from "@ui_kit/QuizPreview/QuizPreview";

interface Props {
  heightSidebar: number;
  mobileSidebar: boolean;
}

export const DesignPage = ({ heightSidebar, mobileSidebar }: Props) => {
  const quiz = useCurrentQuiz();
  const { editQuizId } = useQuizStore();
  const { showConfirmLeaveModal } = useUiTools();
  const theme = useTheme();
  const navigate = useNavigate();
  const currentStep = useQuizStore((state) => state.currentStep);
  const isMobile = useMediaQuery(theme.breakpoints.down(660));
  const [nextStep, setNextStep] = useState<number>(0);

  useEffect(
    () => () => {
      cleanQuestions();
      updateModalInfoWhyCantCreate(false);
      updateSomeWorkBackend(false);
    },
    [],
  );

  useEffect(() => {
    if (editQuizId === null) navigate("/list");
  }, [navigate, editQuizId]);

  const followNewPage = () => {
    setShowConfirmLeaveModal(false);
    setCurrentStep(nextStep);
  };

  const changePage = (index: number) => {
    if (currentStep === 2) {
      setNextStep(index);
      setShowConfirmLeaveModal(true);

      return;
    }

    setCurrentStep(index);
  };

  if (quiz === undefined)
    return (
      <Skeleton sx={{ width: "100vw", height: "100vh", transform: "none" }} />
    );
  return (
    <>
      <Box sx={{ display: "flex", flexDirection: isMobile ? "column" : "row" }}>
        <DesignFilling
          mobileSidebar={mobileSidebar}
          heightSidebar={heightSidebar}
        />
      </Box>
      <ConfirmLeaveModal
        open={showConfirmLeaveModal}
        follow={followNewPage}
        cancel={() => setShowConfirmLeaveModal(false)}
      />
    </>
  );
};
