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


const PADDING = 10;
const WIDGET_DEFAULT_WIDTH = "600px";
const WIDGET_DEFAULT_HEIGHT = "800px";

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

export default function QuizSideButton({
    quizId,
    position,
    buttonBackgroundColor,
    buttonTextColor,
    dimensions,
    fullScreen = false,
    buttonFlash = false,
    autoOpenTime = 0,
    autoShowQuizTime = null,
    hideOnMobile = false,
}: Props) {
    const [isQuizShown, setIsQuizShown] = useState<boolean>(false);
    const isMobile = useMediaQuery("(max-width: 600px)");
    const isQuizCompleted = useQuizCompletionStatus(quizId);
    const [isFlashEnabled, setIsFlashEnabled] = useState<boolean>(buttonFlash);
    const isWidgetHidden = useAutoOpenTimer(autoOpenTime);
    const preventQuizAutoShowRef = useRef<boolean>(false);

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

        const timeout = setTimeout(() => {
            if (!preventQuizAutoShowRef.current) setIsQuizShown(true);
        }, autoShowQuizTime * 1000);

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

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

    if (hideOnMobile && isMobile) return null;

    return createPortal(
        <ThemeProvider theme={lightTheme}>
            <QuizDialog
                open={isQuizShown}
                quizId={quizId}
                onClose={() => setIsQuizShown(false)}
                hideBackdrop
                disableScrollLock
                paperSx={[
                    {
                        m: 0,
                    },
                    !(isMobile || fullScreen) && {
                        position: "absolute",
                        bottom: PADDING,
                        right: position === "right" ? PADDING : undefined,
                        left: position === "left" ? PADDING : undefined,
                        width: dimensions?.width ?? WIDGET_DEFAULT_WIDTH,
                        maxWidth: `calc(100% - ${PADDING * 2}px)`,
                        height: dimensions?.height ?? WIDGET_DEFAULT_HEIGHT,
                        maxHeight: `calc(100% - ${PADDING * 2}px)`,
                    },
                    (isMobile || fullScreen) && {
                        position: "relative",
                        width: "100%",
                        height: "100%",
                        maxHeight: "100%",
                        borderRadius: 0,
                    },
                ]}
            />
            <Fade in={!isWidgetHidden} timeout={400}>
                <Button
                    className="pena-quiz-widget-button"
                    variant="contained"
                    onClick={openQuiz}
                    disableFocusRipple
                    sx={[
                        {
                            display: isQuizShown ? "none" : "block",
                            position: "fixed",
                            height: "70px",
                            width: "600px",
                            maxWidth: `calc(100% - ${PADDING * 2}px)`,
                            backgroundColor: buttonBackgroundColor,
                            color: buttonTextColor,
                            overflow: "hidden",
                        },
                        position === "left" && {
                            bottom: PADDING,
                            left: PADDING,
                        },
                        position === "right" && {
                            bottom: PADDING,
                            right: PADDING,
                        },
                    ]}
                >
                    Пройти квиз
                    {!isQuizCompleted && isFlashEnabled && <RunningStripe />}
                </Button>
            </Fade>
        </ThemeProvider>,
        document.body
    );
}
