import { Box, IconButton, ThemeProvider } from "@mui/material";
import { toggleQuizPreview, useQuizPreviewStore } from "@root/quizPreview";
import { useLayoutEffect, useRef } from "react";
import { Rnd } from "react-rnd";
import { useWindowSize } from "../../utils/hooks/useWindowSize";
import QuizPreviewLayout from "./QuizPreviewLayout";
import ResizeIcon from "@icons/ResizeIcon";
import { themesPublication } from "@utils/themes/Publication/themePublication";
import { useCurrentQuiz } from "@root/quizes/hooks";

const DRAG_PARENT_MARGIN = 0;
const NAVBAR_HEIGHT = 0;
const DRAG_PARENT_BOTTOM_MARGIN = 0;

interface RndPositionAndSize {
  x: number;
  y: number;
  width: string;
  height: string;
}

export default function QuizPreview() {
  const isPreviewShown = useQuizPreviewStore((state) => state.isPreviewShown);
  const rndParentRef = useRef<HTMLDivElement>(null);
  const quiz = useCurrentQuiz();
  const rndRef = useRef<Rnd | null>(null);
  const rndPositionAndSizeRef = useRef<RndPositionAndSize>({
    x: 0,
    y: 0,
    width: "340",
    height: "480",
  });
  const isFirstShowRef = useRef<boolean>(true);

  useLayoutEffect(
    function stickPreviewToBottomRight() {
      const rnd = rndRef.current;
      const rndSelfElement = rnd?.getSelfElement();
      if (
        !rnd ||
        !rndSelfElement ||
        !rndParentRef.current ||
        !isFirstShowRef.current
      )
        return;

      const rndParentRect = rndParentRef.current.getBoundingClientRect();
      const rndRect = rndSelfElement.getBoundingClientRect();

      const x = rndParentRect.width - rndRect.width;
      const y = rndParentRect.height - rndRect.height;

      rnd.updatePosition({ x, y });
      rndPositionAndSizeRef.current.x = x;
      rndPositionAndSizeRef.current.y = y;

      isFirstShowRef.current = false;
    },
    [isPreviewShown],
  );

  return (
    <ThemeProvider
      theme={themesPublication?.[quiz?.config.theme || "StandardTheme"]}
    >
      <Box
        ref={rndParentRef}
        data-cy="quiz-preview-container"
        sx={{
          position: "fixed",
          top: NAVBAR_HEIGHT + DRAG_PARENT_MARGIN,
          left: DRAG_PARENT_MARGIN,
          bottom: 70,
          right: 70,
          // backgroundColor: "rgba(0, 100, 0, 0.2)",
          pointerEvents: "none",
          zIndex: 100,
        }}
      >
        {isPreviewShown && (
          <Rnd
            minHeight={20}
            minWidth={20}
            bounds="parent"
            ref={rndRef}
            dragHandleClassName="quiz-preview-draghandle"
            default={{
              x: rndPositionAndSizeRef.current.x,
              y: rndPositionAndSizeRef.current.y,
              width: rndPositionAndSizeRef.current.width,
              height: rndPositionAndSizeRef.current.height,
            }}
            onResizeStop={(e, direction, ref, delta, position) => {
              rndPositionAndSizeRef.current.x = position.x;
              rndPositionAndSizeRef.current.y = position.y;
              rndPositionAndSizeRef.current.width = ref.style.width;
              rndPositionAndSizeRef.current.height = ref.style.height;
            }}
            onDragStop={(e, d) => {
              rndPositionAndSizeRef.current.x = d.x;
              rndPositionAndSizeRef.current.y = d.y;
            }}
            onDragStart={(e, d) => {
              e.preventDefault();
            }}
            enableResizing={{
              topLeft: isPreviewShown,
            }}
            resizeHandleComponent={{
              topLeft: <ResizeIcon />,
            }}
            resizeHandleStyles={{
              topLeft: {
                top: "-1px",
                left: "-1px",
              },
            }}
            style={{
              overflow: "hidden",
              pointerEvents: "auto",
              boxShadow: "0px 5px 10px 2px rgba(34, 60, 80, 0.2)",
            }}
            cancel=".cancel"
          >
            <QuizPreviewLayout />
          </Rnd>
        )}
      </Box>
    </ThemeProvider>
  );
}
