import styled, { keyframes } from "styled-components";
import { useState, useEffect, useMemo, useRef } from "react";
import { useNavigate, Navigate } from "react-router-dom";
// import score chart.json
import { Share, Download } from "../../components/Icons";
import RollupButton, { THEMES } from "../../components/RollupButton"
import Footer from "../../components/PageLayout/Footer";
import ShareTitleModal from "./ShareTitleModal";
import { ImageWrapper } from "../../components/MediaWrapper";
import getPathPrefix from "../../utils/getPathPrefix";
import { respondTo } from "../../utils/responsive";
import TaskList from "./TaskList";
import { Link } from "react-router-dom";
import { ScrollDown } from "../../components/Icons";
import { getPosition, scrollTo } from "../../utils/scrollTo";
import LoadResultImg from "../GamePage/LoadResult/LoadResultImg";
import ResultImgModal from "./ResultImgModal";


function ResultPage() {
    const [resultData, setResultData] = useState(null);
    const [isShareTitleModalOpen, setIsShareTitleModalOpen] = useState(false);
    const [isResultImgModalOpen, setIsResultImgModalOpen] = useState(false);
    const [resultImgSrc, setResultImgSrc] = useState(null);
    const [isLoaded, setIsLoaded] = useState(false);

    const DOMAIN = process.env.REACT_APP_DOMAIN;

    const navigate = useNavigate();

    const shareUrl = useMemo(() => {
        if (!resultData) return null;
        const DOMAIN = process.env.REACT_APP_DOMAIN;
        const PATH_PREFIX = process.env.REACT_APP_PATH_PREFIX;
        return `${DOMAIN}${PATH_PREFIX}/shares/level-${resultData.level.level}.html`;
    }, [resultData]);


    useEffect(() => {
        // get the chapter data from the local storage
        const result = localStorage.getItem("RESULT");
        setResultData(JSON.parse(result));
        setIsLoaded(true);

        // clear local storage if user close the tab
        // window.addEventListener("beforeunload", () => {
        //     localStorage.removeItem("RESULT");
        //     localStorage.removeItem("CHAPTER_DATA");
        // });

        // return () => {
        //     localStorage.removeItem("RESULT");
        //     localStorage.removeItem("CHAPTER_DATA");
        // }

    }, []);


    const downloadResultImg = () => {
        if (!resultImgSrc) return;
        setIsResultImgModalOpen(true);
    }

    const restart = () => {
        setResultData(null);

        navigate(getPathPrefix("/"));
    }

    const scrollToTaskSection = () => {
        const taskSection = document.getElementById("task-section");
        const contentContainer = document.querySelector(".result-page");

        const position = getPosition(taskSection).y;
        // scroll content container to task section
        scrollTo(1, position, contentContainer);
        
    }

    const handleImgDone = (img) => {
        setResultImgSrc(img);
    }


    if (!isLoaded) return null;
    if (!resultData?.level) return <Navigate to={getPathPrefix("/")} replace />;
    
    return (
        <StyledContainer className="result-page">
            <LoadResultImg onDone={handleImgDone} />
            <ResultImgModal
                isOpen={isResultImgModalOpen}
                imgSrc={resultImgSrc}
                onClose={() => setIsResultImgModalOpen(false)}
            />
            <ShareTitleModal
                isOpen={isShareTitleModalOpen}
                shareUrl={shareUrl}
                onClose={() => setIsShareTitleModalOpen(false)}
            />
            <KVSection>
                <div className="content-wrapper">
                    <ImageWrapper
                        className="level-image"
                        src={resultData?.level.image}
                        m_src={`/images/result/mobile-level.png`}
                        alt="level-image"
                    />
                    <ImageWrapper
                        className="level-kv"
                        src={resultData?.level.gif}
                        alt="level-image"
                    />
                    <KVText>
                        <h2>
                            <ImageWrapper
                                src={resultData?.level.title}
                                alt="level-title"
                            />
                        </h2>
                        <h3>
                            根據真實統計，你的準備指數為
                            <b>{resultData?.rank}</b>
                            分。
                            <br />比{" "}
                            <b>
                                {resultData?.pr > 60
                                    ? resultData?.pr
                                    : 100 - resultData?.pr}
                                ％
                            </b>{" "}
                            的玩家還{resultData?.pr > 60 ? "高" : "低"}。
                        </h3>
                        <p>{resultData?.level.description}</p>
                        <CTABlock>
                            <p>
                                颱好玩就要一直玩(ΦωΦ)
                                <br />
                                快將遊戲結果分享給你的親朋好友！
                            </p>
                            <div>
                                <RollupButton
                                    icon={<Share />}
                                    text="分享測驗連結"
                                    onClick={() =>
                                        setIsShareTitleModalOpen(true)
                                    }
                                />
                                <RollupButton
                                    icon={<Download />}
                                    text={
                                        resultImgSrc
                                            ? "下載結果分享圖"
                                            : "結果圖產生中..."
                                    }
                                    theme={THEMES.DARK}
                                    onClick={downloadResultImg}
                                />
                            </div>
                        </CTABlock>
                    </KVText>
                </div>
                <ScrollDownButton onClick={scrollToTaskSection}>
                    <ScrollDown />
                    下滑看更多
                    <ScrollDown />
                </ScrollDownButton>
            </KVSection>
            <TaskSection id="task-section">
                <div className="task-list-wrapper">
                    {resultData?.tasks.missed?.length > 0 && (
                        <TaskList
                            title="！有幾個重要防颱準備漏掉了！"
                            tasks={resultData?.tasks.missed}
                        />
                    )}
                    {resultData?.tasks.done?.length > 0 && (
                        <TaskList
                            title="！你完美準備的防颱物品！"
                            tasks={resultData?.tasks.done}
                            isDoneList
                        />
                    )}
                </div>
                <EndingSection>
                    <h4>從數據到行動，讓防災更貼近生活</h4>
                    <p>
                        「颱會準備了吧」的誕生靈感來自於2022年減災資料數據溝通競賽的第三名作品──「Typhoon
                        Journey」。該作品以莫拉克風災的真實資料為基礎，透過機器學習分析1,485筆數據，深入探討影響生存率的關鍵因素，成功將複雜的數據轉化為直觀易懂的互動遊戲，並榮獲佳績。
                        <br />
                        <br />
                    </p>
                    <p>
                        我們延續這項創意，將資料分析與風險預測結合，打造出更豐富、更貼近生活的「颱會準備了吧」。我們的目標不只是設計一款遊戲，更希望透過遊戲讓防災知識自然地融入每個人的生活中。
                        <br />
                        <br />
                    </p>
                    <p>
                        為了達成這個目標，我們採用了吸引人的視覺設計與當紅的AI技術，讓玩家在輕鬆互動的過程中，逐步學會如何面對災害風險。透過分數評比與分享機制，我們希望激發玩家挑戰自我、持續學習防災知識，進一步連結至「防災易起來」平台，學習如何善用各種工具來保護自己與家人。
                        <br />
                        <br />
                    </p>
                    <p>
                        「颱會準備了吧」不僅是一款遊戲，更是一場從數據啟發到行動實踐的防災革命。
                        <br />
                        <br />
                        製作團隊：國家災害防救科技中心、簡訊設計
                        <br />
                        原始創意：簡詩汶、江晨瑜、李世寰
                    </p>
                    <div className="link-group">
                        <a
                            href={DOMAIN}
                            target="_blank"
                            rel="noopener noreferrer"
                        >
                            到防災易起來
                            <br />
                            提高防颱生存率
                        </a>
                        <Link to={getPathPrefix("/knowledge")}>
                            看更多
                            <br />
                            防災知識補給
                        </Link>
                        <button onClick={restart}>再玩一次</button>
                    </div>
                </EndingSection>
                <Footer className="footer" />
            </TaskSection>
        </StyledContainer>
    );
}

const StyledContainer = styled.div`
    width: 100vw;
    height: 100vh;
    overflow-y: scroll;

    .user-level-share-img {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 1000;
    }
`;

const KVSection = styled.div`
    width: 100vw;
    background-image: url(${getPathPrefix("/images/result/kv-bg.jpg")});
    background-size: cover;
    background-position: center;

    border-radius: 0px 0px 80px 80px;
    padding-top: 114px;
    padding-bottom: 50px;

    position: relative;
    z-index: 1;

    ${respondTo.sm} {
        border-radius: 0px 0px 40px 40px;
        padding-top: 30px;
        padding-bottom: 20px;

    }

    .content-wrapper {
        width: 952px;
        height: 630px;
        margin: 0 auto;

        position: relative;

        ${respondTo.sm} {
            --width: calc(100vw);
            --height: calc(var(--width) * 790 / 375);
            width: var(--width);
            height: var(--height);

            display: flex;
            flex-direction: column;
            align-items: center;

            padding-top: calc(var(--header-height) + 18.4% + 20px);
        }

        .level-image {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .level-kv {
            position: absolute;
            --size: 354px;
            width: var(--size);
            height: var(--size);
            border-radius: 30px;
            border: 6px solid var(--neutrals-700);

            top: 156px;
            left: 94px;

            ${respondTo.sm} {
                --size: calc(100vw - 140px);
                position: relative;
                top: unset;
                left: unset;
                /* top: 18.4%;
                left: 50%;
                transform: translateX(-50%); */
            }
        }
    }
`;

const scrollDownAnimation = keyframes`
    0% {
        transform: translateY(0);
    }
    100% {
        transform: translateY(4px);
    }
`

const ScrollDownButton = styled.button`
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translate(-50%, 50%);

    background: #ff9500;
    width: 240px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    font: var(--paragraph-1);
    font-weight: 700;
    color: white;
    height: 48px;
    border-radius: 100px;

    svg {
        animation: ${scrollDownAnimation} 0.4s infinite alternate;
    }


`;

const KVText = styled.div`
    position: absolute;
    width: 387px;

    top: 150px;
    left: 496px;
    color: var(--neutrals-700);

    ${respondTo.sm} {
        width: calc(100vw - 120px);
        position: relative;
        top: unset;
        left: unset;

        display: flex;
        flex-direction: column;
        align-items: center;
        margin-top: 12px;
    }

    h2 {
        img {
            height: 95px;
            width: auto;

            ${respondTo.sm} {
                height: 60px;
                margin: 0 auto;

            }
        }
    }

    h3 {
        font-size: 20px;
        font-style: normal;
        font-weight: 700;
        line-height: 120%; /* 24px */
        margin-bottom: 16px;

        ${respondTo.sm} {
            font-size: 14px;
            text-align: center;
            margin-bottom: 8px;
        }

        b {
            font-family: "Bungee", sans-serif;
            font-size: 30px;
            font-style: normal;
            font-weight: 400;
            line-height: 120%;

            ${respondTo.sm} {
                font-size: 20px;
            }
        }
    }

    p {
        font: var(--small-text-1);

        ${respondTo.sm} {
            font: var(--mobile-small-text-1);
        }
    }
`;

const CTABlock = styled.div`
    margin-top: 16px;
    border-radius: 8px;
    background: var(--main-color-b);
    padding: 16px;

    ${respondTo.sm} {
        padding: 8px 24px;
        margin-top: 8px;
        width: 100%;
    }

    p {
        font: var(--paragraph-2);
        font-weight: 700;
        text-align: center;
        margin-bottom: 12px;

        ${respondTo.sm} {
            font: var(--mobile-small-text-1);
            font-weight: 700;
        }
    }

    div {
        display: flex;
        gap: 8px;
        justify-content: center;

        ${respondTo.sm} {
            flex-direction: column;

            button {
                display: flex;
                align-items: center;
                justify-content: center;
                font: var(--small-text-1);
                font-weight: 700;
                padding: 8px;
            }
        }
    }
`;

const TaskSection = styled.div`
    background-image: url(${getPathPrefix('/images/game/start-bg.jpg')});
    background-size: cover;
    background-position: center;

    margin-top: -80px;
    padding: 52px;
    padding-top: calc(52px + 80px);
    padding-bottom: calc(72px + 112px);

    position: relative;

    ${respondTo.sm} {
        // padding: 20px;
        padding-left: 20px;
        padding-right: 20px;
        padding-top: calc(20px + 120px);
        
    }

    .footer {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
    }

    .task-list-wrapper {
        display: flex;
        flex-direction: column;
        gap: 32px;
    }
`;

const EndingSection = styled.div`
    background: white;
    width: 716px;
    margin: 0 auto;
    margin-top: 72px;
    padding: 38px;
    border-radius: 20px;
    border: 4px solid var(--neutrals-700);
    color: var(--neutrals-700);
    padding-bottom: 60px;

    position: relative;

    ${respondTo.sm} {
        width: 100%;
        padding: 24px;
        padding-bottom: 0;
        padding-top: 34px;
    }

    h4 {
        font: var(--headline-5);
        text-align: left;
        margin-bottom: 16px;

        ${respondTo.sm} {
            font: var(--mobile-headline-5);
        }
    }

    p {
        font: var(--paragraph-2);
        text-align: left;

        ${respondTo.sm} {
            font: var(--mobile-paragraph-2);
        }

        &:not(:first-of-type) {
            margin-top: 16px;
        }
    }

    .link-group {
        display: flex;
        gap: 24px;

        position: absolute;
        left: 50%;
        bottom: 0;
        transform: translate(-50%, 50%);

        ${respondTo.sm} {
            flex-direction: column;
            gap: 16px;

            position: relative;
            left: unset;
            bottom: unset;
            transform: unset;

            margin-bottom: -20px;
            margin-top: 36px;

            width: 100%;
            padding: 0 16px;
            
        }


        a, button {
            padding: 12px 16px;
            border-radius: 8px;
            border: 3px solid var(--neutrals-700);

            text-align: center;
            font: var(--paragraph-2);
            font-weight: 700;
            background: white;

            display: flex;
            align-items: center;
            justify-content: center;

            width: 170px;
            box-shadow: 5px 4px 0px 0px #2b3247;
            transition: all 0.2s ease;

            ${respondTo.sm} {
                width: 100%;
                font: var(--mobile-paragraph-2);
                font-weight: 700;

                br {
                    display: none;
                }
            }

            &:hover {
                background: var(--main-color-a);
                transform: translate(5px, 4px);
                box-shadow: 0px 0px 0px 0px #2b3247;
            }
        }
    }
`;

export default ResultPage ;

