import styled from "styled-components";
import ChapterCover from "../ChapterCover";
import { THEMES, GoButton} from "../../../components/BorderShadowButton";
import { useState, useEffect, useRef, useCallback } from "react";
import GameObjectModal from "../GameObjectModal";
import GAME_OBJECTS from "./GAME_OBJECTS";
import DoneModal from "./DoneModal";
import { useGameContext, GAME_STATES } from "..";
import { DISPATCH_PLAY_MUSIC } from "../AudioController";
import { ImageWrapper } from "../../../components/MediaWrapper";
import { useMediaSelectTo, breakpoints, respondTo } from "../../../utils/responsive";
import MobileGameUI from "../MobileGameUI";
import GameContentFrame from "../GameContentFrame";
import CatPawIntro from "../CatPawIntro";
import GameUI from "../GameUI";
import Background from "../Background";
import GameObjectLayers from "../GameObjectLayers";
import useGameObjectState from "../useGameObjectState";


const CHAPTER_STATES = {
    COVER: "cover",
    INTRO: "intro",
    GAME: "game",
    PAUSE: "pause",
}

const COUNTDOWN = 60; // seconds


function Chapter3() {
    const { endChapter } = useGameContext();
    const [currentState, setCurrentState] = useState(CHAPTER_STATES.COVER);
    const [isTimerFinished, setIsTimerFinished] = useState(false);
    const [isDoneModalOpen, setIsDoneModalOpen] = useState(false);
    const {
        selectedObject,
        setSelectedObject,
        readyObjects,
        hoveredObjectId,
        doneObjectIds,
        handleObjectSelect,
        handleObjectMouseEnter,
        handleObjectMouseLeave,
        handleReadyButtonClick,
        cancelObject,
        isPrepared,
    } = useGameObjectState(GAME_OBJECTS);

    const isMobile = useMediaSelectTo(breakpoints.sm);
    const mobileGameFrameRef = useRef(null);
    const scrollHintRef = useRef(null);
    const isScrollHintShown = useRef(false);

    const showDoneModal = () => {
        setIsDoneModalOpen(true);
    };

    const handleEndGame = () => {
        endChapter("chapter3", readyObjects, GAME_STATES.CHAPTER4, true);
    };

    const handleTimerFinished = useCallback(() => {
        setIsTimerFinished(true);
        showDoneModal();    
    }, []);


    const showScrollHintAndHide = () => {
        if (isScrollHintShown.current) return;
        isScrollHintShown.current = true;
        scrollHintRef.current.classList.add("is--in");

        const hideScrollHint = () => {
            if (!scrollHintRef.current) return;
            if (scrollHintRef.current.classList.contains("is--in")) {
                scrollHintRef.current.classList.remove("is--in");
            }
        };

        setTimeout(() => {
            hideScrollHint();
        }, 2000);

        const frameWrapper =
            mobileGameFrameRef.current.querySelector(".frame-wrapper");
        frameWrapper.addEventListener("touchstart", hideScrollHint);
    };

    useEffect(() => {
        DISPATCH_PLAY_MUSIC("/audios/03.mp3");
    }, []);

    return (
        <>
            <GameObjectModal
                onClose={() => {
                    setSelectedObject(null);
                    setCurrentState(CHAPTER_STATES.GAME);
                }}
                isOpen={selectedObject !== null}
                number={selectedObject?.number}
                image={selectedObject?.image}
                title={selectedObject?.title}
                description={selectedObject?.description}
                button={
                    !isPrepared(selectedObject?.id) ? (
                        <ReadyButton onClick={handleReadyButtonClick}>
                            確定準備
                        </ReadyButton>
                    ) : (
                        <CancelButton onClick={cancelObject}>
                            取消準備
                        </CancelButton>
                    )
                }
            />
            <DoneModal
                isOpen={isDoneModalOpen}
                onClose={() => {
                    setCurrentState(CHAPTER_STATES.GAME);
                    setIsDoneModalOpen(false);
                }}
                onNext={handleEndGame}
                canClose={isTimerFinished === false}
            />
            <StyledContainer>
                {currentState === CHAPTER_STATES.COVER && (
                    <ChapterCover
                        cover="/images/game/chapter3/intro.webp"
                        cover_m="/images/game/chapter3/intro-m.webp"
                        chapterIndex={3}
                        mainTitle="抗颱準備"
                        subTitle="採買完快回家準備防颱準備，為預防颱風對住家及周遭破壞的可能做準備"
                        className="chapter-cover"
                        btnText="開始準備"
                        onNextClick={() =>
                            setCurrentState(CHAPTER_STATES.INTRO)
                        }
                    />
                )}

                <CatPawIntro
                    image="/images/game/chapter3/intro.png"
                    className="cat-paw-intro"
                    isIn={currentState === CHAPTER_STATES.INTRO}
                    onClick={() => {
                        setCurrentState(CHAPTER_STATES.GAME);
                        if (window.innerWidth <= breakpoints.sm) {
                            showScrollHintAndHide();
                        }
                    }}
                />
                {isMobile && (
                    <MobileGameUI
                        isShow={currentState !== CHAPTER_STATES.COVER}
                        isTutorialModalOpen={
                            currentState === CHAPTER_STATES.INTRO
                        }
                        timerShouldStart={currentState === CHAPTER_STATES.GAME}
                        onTimerFinished={handleTimerFinished}
                        timerSeconds={COUNTDOWN}
                        openTutorial={() =>
                            setCurrentState(CHAPTER_STATES.INTRO)
                        }
                    />
                )}

                <GameView ref={mobileGameFrameRef}>
                    <GameContentFrame>
                        <Background
                            className="bg"
                            bg="/images/game/chapter3/bg.webp"
                            bg_m="/images/game/chapter3/bg.webp"
                        />
                        <ImageWrapper
                            src="/images/game/chapter3/house.webp"
                            className="bg"
                            alt=""
                        />
                        <GameUI
                            gameState={currentState}
                            isMobile={isMobile}
                            COUNTDOWN={COUNTDOWN}
                            CHAPTER_STATES={CHAPTER_STATES}
                            handleTimerFinished={handleTimerFinished}
                            openTutorial={() =>
                                setCurrentState(CHAPTER_STATES.INTRO)
                            }
                        />
                        <GameObjectLayers
                            gameObjects={GAME_OBJECTS}
                            doneObjectIds={doneObjectIds}
                            hoveredObjectId={hoveredObjectId}
                            onSelect={handleObjectSelect}
                            onMouseEnter={handleObjectMouseEnter}
                            onMouseLeave={handleObjectMouseLeave}
                        />
                        <div className="scroll-hint" ref={scrollHintRef}>
                            <ImageWrapper src="/images/game/scroll-hint.png" />
                        </div>
                    </GameContentFrame>
                    <GoButton
                        className="finish-button"
                        text="處理完畢"
                        size="s"
                        theme={THEMES.DARK}
                        onClick={showDoneModal}
                    />
                </GameView>
            </StyledContainer>
        </>
    );
}

const StyledContainer = styled.div`
    width: 100%;
    height: 100%;
    cursor: none;

    .chapter-cover {
        z-index: 2;
    }
`;

const GameView = styled.div`
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;

    video,
    .bg,
    .layer {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;

        pointer-events: none;
    }

    .scroll-hint {
        display: block;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 10;

        opacity: 0;
        pointer-events: none;
        z-index: 10;

        transition: opacity 0.2s ease-out;

        width: 100%;
        height: 100%;

        display: flex;
        justify-content: center;
        align-items: center;
        backdrop-filter: blur(2px);

        img {
            width: 268px;
            height: 34px;
        }

        &.is--in {
            opacity: 1;
            pointer-events: auto;
        }
    }

    .cart-button {
        position: absolute;
        bottom: 28px;
        left: 28px;
        z-index: 1;
    }

    .finish-button {
        cursor: none;
        position: absolute;
        bottom: 28px;
        right: 28px;
        z-index: 1;
    }

    .layer {
        position: absolute;
        border: 0;
        background: transparent;
        padding: 0;
        cursor: none;

        .done,
        .default {
            pointer-events: none;
        }

        .button {
            pointer-events: auto;
        }

        .default {
            opacity: 1;
        }

        .done {
            opacity: 0;
        }
        &.hover {
            .default,
            .done {
                filter: drop-shadow(1px 2px 0px #4d4d4d)
                    drop-shadow(7px 7px 0px #ff7424)
                    drop-shadow(-5px -2px 0px #ffd45c);
            }

            ${respondTo.sm} {
                .default,
                .done {
                    filter: none;
                }
            }
        }
    }

    .object-layer {
        z-index: 3;
        pointer-events: auto;

        img {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            object-fit: fill;
        }
    }

    .decor-layer {
        position: absolute;
        z-index: 2;
        pointer-events: none;

        img {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            object-fit: fill;
        }
    }
    .layer.done {
        .default {
            opacity: 0;
        }

        .done {
            opacity: 1;
        }
    }
`;



const Button = styled.button`
    color: #fff;
    border-radius: 8px;
    padding: 10px 20px;

    font: var(--headline-6);
`;

const ReadyButton = styled(Button)`
    background: var(--neutrals-700);
`;

const CancelButton = styled(Button)`
    background: #ff6f2c; 
`;

export default Chapter3;