import { useQuizData } from "@/api/hooks";
import { BannerWidgetComponentProps } from "@/model/widget/banner";
import lightTheme from "@/utils/themes/light";
import { Box, Button, Fade, IconButton, ThemeProvider, Typography, useMediaQuery } from "@mui/material";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import BannerIcon from "../shared/BannerIcon";
import QuizDialog from "../shared/QuizDialog";
import RunningStripe from "../shared/RunningStripe";
import { colorArrayToHex, darkenColor, parseColor } from "../shared/colorUtils";
import { useAutoOpenTimer } from "../shared/useAutoOpenTimer";

const PADDING = 10;

export default function QuizBanner({
  quizId,
  position,
  onWidgetClose,
  appealText = "Пройти тест",
  quizHeaderText = "Заголовок квиза",
  buttonTextColor,
  buttonBackgroundColor,
  autoShowQuizTime = null,
  openOnLeaveAttempt,
  buttonFlash = false,
  hideOnMobile,
  withShadow = false,
  rounded = false,
  bannerFullWidth = false,
  pulsation = false,
  autoShowWidgetTime = 0,
  dialogDimensions,
  fullScreen = false,
}: BannerWidgetComponentProps) {
  const isMobile = useMediaQuery("(max-width: 600px)");
  const [isQuizShown, setIsQuizShown] = useState<boolean>(false);
  const [isFlashEnabled, setIsFlashEnabled] = useState<boolean>(buttonFlash);
  const isWidgetHidden = useAutoOpenTimer(autoShowWidgetTime);
  const { data: quizData } = useQuizData(quizId);
  const preventQuizAutoShowRef = useRef<boolean>(false);
  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.documentElement.addEventListener("mouseleave", handleMouseLeave);

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

  function openQuiz() {
    preventQuizAutoShowRef.current = true;
    setIsQuizShown(true);
    setIsFlashEnabled(false);
  }

  if (hideOnMobile && isMobile) return null;
  if (!quizData) return null;

  const isQuizCompleted = quizData.settings.cfg.antifraud ? quizData.recentlyCompleted : false;
  const showButtonFlash = !isQuizCompleted && isFlashEnabled;

  let hoverBackgroundColor = buttonBackgroundColor;
  if (buttonBackgroundColor) {
    const color = parseColor(buttonBackgroundColor);
    if (color) hoverBackgroundColor = colorArrayToHex(darkenColor(color, 0.7));
  }

  return createPortal(
    <ThemeProvider theme={lightTheme}>
      <Fade in={!isQuizShown && !isWidgetHidden}>
        <Box
          className="pena-quiz-widget-banner"
          sx={[
            {
              position: "fixed",
              height: "120px",
              width: bannerFullWidth ? "100%" : "800px",
              maxWidth: bannerFullWidth ? "100%" : `calc(100% - ${PADDING * 2}px)`,
            },
            position === "topleft" && {
              top: bannerFullWidth ? 0 : PADDING,
              left: bannerFullWidth ? 0 : PADDING,
            },
            position === "topright" && {
              top: bannerFullWidth ? 0 : PADDING,
              right: bannerFullWidth ? 0 : PADDING,
            },
            position === "bottomleft" && {
              bottom: bannerFullWidth ? 0 : PADDING,
              left: bannerFullWidth ? 0 : PADDING,
            },
            position === "bottomright" && {
              bottom: bannerFullWidth ? 0 : PADDING,
              right: bannerFullWidth ? 0 : PADDING,
            },
            pulsation && {
              ":before": {
                content: "''",
                position: "absolute",
                height: "100%",
                width: "100%",
                pointerEvents: "none",
                willChange: "box-shadow",
                borderRadius: rounded && !bannerFullWidth ? "8px" : 0,
                animation: "pena-pulsation linear 5s infinite",
                "@keyframes pena-pulsation": {
                  "0%": {
                    boxShadow: "0 0 0 0 rgba(126, 42, 234, 0.5)",
                  },
                  "30%": {
                    boxShadow: "0 0 0 15px rgba(0, 0, 0, 0)",
                  },
                  "100%": {
                    boxShadow: "0 0 0 0 rgba(0, 0, 0, 0)",
                  },
                },
              },
            },
          ]}
        >
          <Button
            onClick={openQuiz}
            variant="contained"
            sx={[
              {
                display: "flex",
                gap: "20px",
                overflow: "hidden",
                height: "100%",
                width: "100%",
                px: "28px",
                color: buttonTextColor,
                backgroundColor: buttonBackgroundColor,
                borderRadius: rounded && !bannerFullWidth ? "8px" : 0,
                justifyContent: "start",
                ":hover": {
                  backgroundColor: hoverBackgroundColor,
                },
              },
              withShadow && {
                boxShadow: "0px 0px 12px 0px rgba(0, 0, 0, 0.7)",
              },
            ]}
          >
            <BannerIcon />
            <Box
              sx={{
                display: "flex",
                flexDirection: "column",
                alignItems: "start",
              }}
            >
              <Typography fontSize="24px" lineHeight="120%">
                {appealText}
              </Typography>
              <Typography fontSize="44px" lineHeight="120%">
                {quizHeaderText}
              </Typography>
            </Box>
            {showButtonFlash && <RunningStripe />}
          </Button>
          <IconButton
            onClick={onWidgetClose}
            sx={{
              position: "absolute",
              top: 0,
              right: 0,
              p: "8px",
              width: "44px",
              height: "44px",
              borderRadius: "4px",
              ":hover": {
                backgroundColor: "rgba(0, 0, 0, 0.3)",
              },
            }}
          >
            <svg viewBox="0 0 7 7" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path
                d="M1.00391 0.757812L6.67266 6.42656M1.00391 6.42656L6.67266 0.757812"
                stroke="white"
                strokeWidth="0.5"
              />
            </svg>
          </IconButton>
        </Box>
      </Fade>
      <QuizDialog
        open={isQuizShown}
        quizId={quizId}
        onClose={() => setIsQuizShown(false)}
        disableScrollLock
        paperSx={[
          isMobile || fullScreen
            ? {
                width: "100%",
                height: "100%",
                maxHeight: "100%",
                borderRadius: 0,
                m: 0,
              }
            : {
                width: dialogDimensions?.width,
                height: dialogDimensions?.height,
              },
        ]}
      />
    </ThemeProvider>,
    document.body
  );
}
