import lightTheme from "@/utils/themes/light";
import { Button, ThemeProvider, useMediaQuery } from "@mui/material";
import { useEffect, useRef, useState } from "react";
import QuizDialog from "../shared/QuizDialog";
import RunningStripe from "../shared/RunningStripe";
import { useQuizCompletionStatus } from "../shared/useQuizCompletionStatus";


const WIDGET_DEFAULT_WIDTH = "600px";
const WIDGET_DEFAULT_HEIGHT = "80%";

interface Props {
    quizId: string;
    fixedSide?: "left" | "right";
    dimensions?: { width: string; height: string; };
    /**
     * Открыть квиз через X секунд, 0 - сразу
     */
    autoShowQuizTime?: number | null;
    hideOnMobile?: boolean;
    openOnLeaveAttempt?: boolean;
    buttonFlash?: boolean;
    withShadow?: boolean;
    rounded?: boolean;
    buttonText?: string;
    buttonTextColor?: string;
    buttonBackgroundColor?: string;
}

export default function OpenQuizButton({
    quizId,
    fixedSide,
    autoShowQuizTime = null,
    dimensions,
    hideOnMobile,
    openOnLeaveAttempt,
    buttonFlash = false,
    withShadow = false,
    rounded = false,
    buttonText = "Пройти квиз",
    buttonTextColor,
    buttonBackgroundColor,
}: Props) {
    const isMobile = useMediaQuery("(max-width: 600px)");
    const [isQuizShown, setIsQuizShown] = useState<boolean>(false);
    const isQuizCompleted = useQuizCompletionStatus(quizId);
    const [isFlashEnabled, setIsFlashEnabled] = useState<boolean>(buttonFlash);
    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.addEventListener("mouseleave", handleMouseLeave);

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

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

    if (hideOnMobile && isMobile) return null;

    return (
        <ThemeProvider theme={lightTheme}>
            <Button
                className="pena-quiz-widget-button"
                onClick={openQuiz}
                variant="contained"
                disableFocusRipple
                sx={[
                    {
                        overflow: "hidden",
                        color: buttonTextColor,
                        backgroundColor: buttonBackgroundColor,
                    },
                    withShadow && {
                        boxShadow: "0px 0px 8px 0px rgba(0, 0, 0, 0.7)",
                    },
                    !rounded && {
                        borderRadius: 0,
                    },
                    Boolean(fixedSide) && {
                        position: "fixed",
                        bottom: "50%",
                    },
                    fixedSide === "left" && {
                        left: 0,
                        transformOrigin: "left",
                        transform: "rotate(-90deg) translateY(50%) translateX(-50%)",
                    },
                    fixedSide === "right" && {
                        right: 0,
                        transformOrigin: "right",
                        transform: "rotate(-90deg) translateY(-50%) translateX(50%)",
                    },
                ]}
            >
                {buttonText}
                {!isQuizCompleted && isFlashEnabled && <RunningStripe />}
            </Button>
            <QuizDialog
                open={isQuizShown}
                quizId={quizId}
                onClose={() => setIsQuizShown(false)}
                paperSx={{
                    width: dimensions?.width ?? WIDGET_DEFAULT_WIDTH,
                    height: dimensions?.height ?? WIDGET_DEFAULT_HEIGHT,
                }}
            />
        </ThemeProvider>
    );
}
