import { useQuizData } from "@/api/hooks";
import { PopupWidgetComponentProps } from "@/model/widget/popup";
import { useMediaQuery } from "@mui/material";
import { useEffect, useRef, useState } from "react";
import QuizDialog from "../shared/QuizDialog";

export default function QuizPopup({
  quizId,
  dialogDimensions,
  autoShowQuizTime = null,
  hideOnMobile = false,
  openOnLeaveAttempt = false,
  fullScreen = false,
}: PopupWidgetComponentProps) {
  const initialIsQuizShown = autoShowQuizTime !== null || openOnLeaveAttempt ? false : true;

  const { data: quizData } = useQuizData(quizId);
  const [isQuizShown, setIsQuizShown] = useState<boolean>(initialIsQuizShown);
  const isMobile = useMediaQuery("(max-width: 600px)");
  const preventOpenOnLeaveAttemptRef = useRef<boolean>(false);

  useEffect(
    function setAutoShowQuizTimer() {
      if (autoShowQuizTime === null || openOnLeaveAttempt) return;

      const timeout = setTimeout(() => {
        setIsQuizShown(true);
      }, autoShowQuizTime * 1000);

      return () => {
        clearTimeout(timeout);
      };
    },
    [autoShowQuizTime, openOnLeaveAttempt]
  );

  useEffect(
    function attachLeaveListener() {
      if (!openOnLeaveAttempt) return;

      const handleMouseLeave = () => {
        if (!preventOpenOnLeaveAttemptRef.current) {
          preventOpenOnLeaveAttemptRef.current = true;
          setIsQuizShown(true);
        }
      };

      document.addEventListener("mouseleave", handleMouseLeave);

      return () => {
        document.removeEventListener("mouseleave", handleMouseLeave);
      };
    },
    [openOnLeaveAttempt]
  );

  if (!quizData) return null;

  const isQuizCompleted = quizData.settings?.cfg?.antifraud ? quizData.recentlyCompleted : false;
  if (isQuizCompleted) return null;
  if (hideOnMobile && isMobile) return null;

  return (
    <QuizDialog
      open={isQuizShown}
      quizId={quizId}
      onClose={() => setIsQuizShown(false)}
      paperSx={[
        isMobile || fullScreen
          ? {
              width: "100%",
              height: "100%",
              maxHeight: "100%",
              borderRadius: 0,
              m: 0,
            }
          : {
              width: dialogDimensions?.width,
              height: dialogDimensions?.height,
            },
      ]}
    />
  );
}
