import styled, { keyframes } from "styled-components";
import { useState, useEffect } from "react";
import { useGameContext, GAME_STATES } from "..";
import { ImageWrapper } from "../../../components/MediaWrapper";
import getPathPrefix from "../../../utils/getPathPrefix";
import { respondTo } from "../../../utils/responsive";
import { DISPATCH_STOP_MUSIC } from "../AudioController";
import calculateScore from "../../ResultPage/calculateResult";
import getCompleteTasks from "../../ResultPage/getCompleteTasks";
import scoreChart from "../../../score-chart.json";
import { getLevel } from "../../ResultPage/getLevel";

const PR_ENDPOINT =
    "https://script.google.com/macros/s/AKfycby_YwDRvdtmvzljBhF1JBZunNm78R_sL9pX9AkacpISNd89L_gHZOxedLnvG0nZKGnegA/exec";

const PROGRESS_TICK_MS = 60;
const PROGRESS_BEFORE_RESULT_STEP = 1.2;

// const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

function LoadResult() {
    const { setGameCurrentState } = useGameContext();
    const [percentage, setPercentage] = useState(0);
    const [isResultReady, setIsResultReady] = useState(false);

    const storeScoreAndGetPR = async (score, tasks, scores) => {
        const body = {
            score: score,
            ...scores,
        };
        let res = null;
        let pr = 0;

        tasks.done.forEach(task => {
            body[task.title] = 1
        });
        tasks.missed.forEach(task => {
            body[task.title] = 0
        });


        try {
            // First try to POST the score
            res = await fetch(PR_ENDPOINT, {
                method: "POST", 
                body: JSON.stringify(body),
                headers: {
                    "Content-Type": "text/plain",
                    // "X-CSRF-Token": csrfToken,
                },
            });
            res = await res.json();
        } catch (e) {
            console.error(e);
        }

        // Get PR score regardless of POST success
        const url = new URL(PR_ENDPOINT);
        url.searchParams.set("score", score);
        
        try {
            const prRes = await fetch(url);
            const prData = await prRes.json();
            pr = prData.pr;
        } catch (e) {
            console.error(e);
            pr = 50; // Default PR if fetch fails
        }
        return pr;
    };

    const getAllResult = async () => {
        const chapterData = localStorage.getItem("CHAPTER_DATA");
        const data = JSON.parse(chapterData);
        const scores = calculateScore(data);
        const tasks = getCompleteTasks(data);

        let rank = 0;
        const ALL_KEYS = [
            "m1_1",
            "m1_2",
            "m1_5",
            "s3",
            "house_strengthen",
            "emergency_kit",
            "damage_posibility",
            "confirm_evacuate",
        ];

        scoreChart.forEach((item) => {
            if (ALL_KEYS.every((key) => item[key] === scores[key])) {
                rank = item.Rank;
            }
        });

        let res = {
            rank,
            level: getLevel(rank),
            pr: 50, // TODO: 換成實際數字
            tasks,
        };

        const pr = await storeScoreAndGetPR(res.rank, tasks, scores);
        res.pr = Math.floor(pr);

        // set to local storage
        localStorage.setItem("RESULT", JSON.stringify(res));
        setIsResultReady(true);
    }

    useEffect(() => {
        getAllResult();
    }, [])

    useEffect(() => {
        const interval = setInterval(() => {
            if (percentage >= 100) {
                clearInterval(interval);
                setGameCurrentState(GAME_STATES.RESULT);
                return;
            }

            if (!isResultReady) {
                setPercentage(prev => Math.min(prev + PROGRESS_BEFORE_RESULT_STEP, 60));
                return;
            }

            setPercentage(100);
        }, PROGRESS_TICK_MS);

        return () => clearInterval(interval);

    }, [percentage, isResultReady, setGameCurrentState]);

    useEffect(() => {
        DISPATCH_STOP_MUSIC();
    }, []);


    return (
        <>
            <StyledContainer>
                <Group>
                    <ProgressGroup>
                    <ImageWrapper
                        src="/images/game/loading-character.png"
                        alt="loading-character"
                    />
                    <div className="progress-container">
                        <div
                            className="progress-bar"
                            style={{ width: `${percentage}%` }}
                        ></div>
                    </div>
                </ProgressGroup>
                <p>LOADING...</p>
                <strong class="shaded-title">
                    <span>你這次防颱準備表現如何呢？一起來看看⋯⋯</span>
                    <span>你這次防颱準備表現如何呢？一起來看看⋯⋯</span>
                    </strong>
                </Group>
            </StyledContainer>
        </>
    );
}

const StyledContainer = styled.div`
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url(${getPathPrefix("/images/game/loading-frame-bg.jpg")}) no-repeat center center;
    background-size: cover;
`;

const sparkling = keyframes`
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
`;

const Group = styled.div`
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

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

    p {
        margin-top: 4px;
        font-family: "Bungee", "Noto Sans TC", sans-serif;
        font-size: 16px;
        font-style: normal;
        font-weight: 400;
        line-height: 120%; /* 19.2px */
        color: var(--neutrals-700);
        text-align: center;
    }

    .shaded-title {
        width: fit-content;
        position: relative;
        isolation: isolate;
        color: var(--main-color-a);
        margin-top: 12px;

        font-size: 20px;
        font-style: normal;
        font-weight: 900;
        line-height: 160%; /* 32px */

        animation: ${sparkling} 1s infinite;
        text-align: center;

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

        span:first-child {
            color: currentColor;
        }

        span:last-child {
            position: absolute;
            z-index: -1;
            left: 0;
            top: 0px;

            width: 100%;
            height: 100%;

            -webkit-text-stroke: 3px var(--neutrals-700);
            text-stroke: 3px var(--neutrals-700);
            color: var(--neutrals-700);
        }
    }
`;

const ProgressGroup = styled.div`
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .progress-container {
        width: 270px;
        height: 26px;
        border: 1px solid red;
        border: 1px solid var(--neutrals-700);
        border-radius: 4px;
        padding: 4px;
        background: var(--neutrals-000);

        .progress-bar {
            width: 20%;
            height: 100%;
            background: var(--neutrals-700);
            border-radius: 2px;
        }
    }
`;


export default LoadResult;