import { quizApi } from "@api/quiz";
import EyeIcon from "@icons/EyeIcon";
import VisibilityIcon from "@mui/icons-material/Visibility";

import {
  Box,
  Button,
  IconButton,
  Switch,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { setQuizes, updateQuiz, setCurrentStep } from "@root/quizes/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { useQuizStore } from "@root/quizes/store";
import Sidebar from "@ui_kit/Sidebar";
import Stepper from "@ui_kit/Stepper";
import SwitchStepPages from "@ui_kit/switchStepPages";
import { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useDebouncedCallback } from "use-debounce";
import { SidebarMobile } from "../../ui_kit/Sidebar/SidebarMobile";
import {
  cleanQuestions,
  createResult,
  setQuestions,
} from "@root/questions/actions";
import {
  updateCanCreatePublic,
  updateModalInfoWhyCantCreate,
  setShowConfirmLeaveModal,
  updateSomeWorkBackend,
} from "@root/uiTools/actions";
import { Header } from "@ui_kit/Header/Header";
import { useQuestionsStore } from "@root/questions/store";
import { questionApi } from "@api/question";
import { useUiTools } from "@root/uiTools/store";

import { AnyTypedQuizQuestion } from "@model/questionTypes/shared";
import { ModalInfoWhyCantCreate } from "./ModalInfoWhyCantCreate";
import { ConfirmLeaveModal } from "./ConfirmLeaveModal";
import { checkQuestionHint } from "@utils/checkQuestionHint";

export default function EditPage() {
  const quiz = useCurrentQuiz();
  const { editQuizId } = useQuizStore();
  const { questions } = useQuestionsStore();
  console.log(questions);
  const { whyCantCreatePublic, showConfirmLeaveModal } = useUiTools();
  const theme = useTheme();
  const navigate = useNavigate();
  const currentStep = useQuizStore((state) => state.currentStep);
  const isBranchingLogic = useMediaQuery(theme.breakpoints.down(1100));
  const isMobile = useMediaQuery(theme.breakpoints.down(660));
  const [nextStep, setNextStep] = useState<number>(0);
  const quizConfig = quiz?.config;
  const [openBranchingPage, setOpenBranchingPage] = useState<boolean>(false);

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

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

  const updateQuestionHint = useDebouncedCallback(
    (questions: AnyTypedQuizQuestion[]) => {
      const problems = checkQuestionHint(questions, quiz);
      useUiTools.setState({ whyCantCreatePublic: problems });
      if (Object.keys(problems).length > 0) {
        updateQuiz(quiz?.id, (state) => {
          state.status = "stop";
        });
        updateCanCreatePublic(false);
      } else {
        updateCanCreatePublic(true);
      }
    },
    600,
  );

  useEffect(() => {
    updateQuestionHint(questions);
  }, [questions, quiz]);

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

  if (!quizConfig) return <></>;

  const isConditionMet =
    [1].includes(currentStep) && quizConfig.type !== "form";

  return (
    <>
      <Box
        sx={{
          display: isMobile ? "block" : "flex",
          position: "relative",
        }}
      >
        <Box
          sx={{
            background: theme.palette.background.default,
            width: "100%",
            overflow: "hidden",
          }}
        >
          <Box
            sx={{
              padding: isMobile ? "16px 16px 20px 16px" : "25px 25px 20px 25px",
              overflow: "auto",
              height: isMobile
                ? `calc(100vh - 125px)`
                : isConditionMet
                  ? isBranchingLogic
                    ? `calc(100vh - 166px)`
                    : `calc(100vh - 186px)`
                  : `calc(100vh - 166px)`,
              boxSizing: "border-box",
            }}
          >
            {/* Выбор текущей страницы редактирования чего-либо - находится здесь */}
            {quizConfig && (
              <>
                <Stepper activeStep={currentStep} />
                <SwitchStepPages
                  activeStep={currentStep}
                  quizType={quizConfig.type}
                  quizResults={quizConfig.results}
                  quizStartPageType={quizConfig.startpageType}
                  openBranchingPage={openBranchingPage}
                  setOpenBranchingPage={setOpenBranchingPage}
                />
              </>
            )}
          </Box>
        </Box>
      </Box>

      <ModalInfoWhyCantCreate />
      <ConfirmLeaveModal
        open={showConfirmLeaveModal}
        follow={followNewPage}
        cancel={() => setShowConfirmLeaveModal(false)}
      />
    </>
  );
}
