import { Box, Skeleton, useMediaQuery, useTheme } from "@mui/material";
import { updateQuiz, setCurrentStep } from "@root/quizes/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { useQuizStore } from "@root/quizes/store";
import Stepper from "@ui_kit/Stepper";
import SwitchStepPages from "@ui_kit/switchStepPages";
import { useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { useDebouncedCallback } from "use-debounce";
import { cleanQuestions } from "@root/questions/actions";
import {
  updateCanCreatePublic,
  updateModalInfoWhyCantCreate,
  setShowConfirmLeaveModal,
  updateSomeWorkBackend,
} from "@root/uiTools/actions";
import { useQuestionsStore } from "@root/questions/store";
import { useUiTools } from "@root/uiTools/store";

import { AnyTypedQuizQuestion } from "@frontend/squzanswerer";
import { ModalInfoWhyCantCreate } from "./ModalInfoWhyCantCreate";
import { ConfirmLeaveModal } from "./ConfirmLeaveModal";
import { checkQuestionHint } from "@utils/checkQuestionHint";
import AmoTokenExpiredDialog from "../IntegrationsPage/IntegrationsModal/Amo/AmoTokenExpiredDialog";
import { useAmoAccount } from "@/api/integration";

interface Props {
  openBranchingPage: boolean;
  setOpenBranchingPage: (a: boolean) => void;
  widthMain: number;
  mobileSidebar: boolean;
  heightSidebar: number;
  scrollDown: boolean;
  setScrollDown: (a: boolean) => void;
}
export default function EditPage({
  openBranchingPage,
  setOpenBranchingPage,
  widthMain,
  mobileSidebar,
  heightSidebar,
  scrollDown,
  setScrollDown,
}: Props) {
  const quiz = useCurrentQuiz();
  const { editQuizId } = useQuizStore();
  const { questions } = useQuestionsStore();
  const { showConfirmLeaveModal, nextStep } = 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(650));
  const quizConfig = quiz?.config;
  const mainBlock = useRef(0);

  const heightBar = heightSidebar + 51 + 88;
  useEffect(() => {
    if (editQuizId === null) navigate("/list");
  }, [navigate, editQuizId]);

  useEffect(
    () => () => {
      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);
  };

  let lastScroll = mainBlock.current.scrollTop;
  const onScroll = (e) => {
    if ((mainBlock.current.scrollTop > lastScroll && !scrollDown) || null) {
      setScrollDown(true);
    }
    if (mainBlock.current.scrollTop < lastScroll && scrollDown) {
      setScrollDown(false);
    }
    lastScroll = mainBlock.current.scrollTop;
  };

  if (!quizConfig) return <Skeleton sx={{width: "100vw", height: "100vh"}}></Skeleton>;

  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
            onScroll={onScroll}
            ref={mainBlock}
            sx={{
              padding: isMobile
                ? mobileSidebar
                  ? `${heightBar}px 16px 70px 16px`
                  : "67px 16px 70px 16px"
                : "25px 25px 20px 25px",
              overflow: "auto",
              height: isMobile
                ? "100vh"
                : isConditionMet
                  ? isBranchingLogic
                    ? `calc(100vh - 166px)`
                    : `calc(100vh - 186px)`
                  : `calc(100vh - 166px)`,
              boxSizing: "border-box",
              transition: "transform 0.3s",
              paddingBottom: scrollDown && isMobile ? "120px" : undefined,
            }}
          >
            {quizConfig && (
              <>
                <Stepper activeStep={currentStep} />
                  <SwitchStepPages
                    activeStep={currentStep}
                    quizType={quizConfig.type}
                    quizResults={quizConfig.results}
                    quizStartPageType={quizConfig.startpageType}
                    openBranchingPage={openBranchingPage}
                    setOpenBranchingPage={setOpenBranchingPage}
                    widthMain={widthMain}
                  />
              </>
            )}
          </Box>
        </Box>
      </Box>
      <ModalInfoWhyCantCreate />
      <ConfirmLeaveModal
        open={showConfirmLeaveModal}
        follow={followNewPage}
        cancel={() => setShowConfirmLeaveModal(false)}
      />
    </>
  );
}
