import { createContext, useContext, useEffect, useState } from "react";
import chantierAtmopshere from "../assets/sounds/chantier_1.mp3";
import GameAnswerExplanation from "../components/game/GameAnswerExplanation.jsx";
import { useGame } from "../hooks/useGame.jsx";
import { useUser } from "../hooks/useUser.jsx";
import { calculateScore } from "../utils/gameFunctions.js";

export const GameContext = createContext();

export function GameContextProvider({ children }) {
	const { language, country } = useUser();

	// ##### DATA #####
	const [contextGameDatas, setContextGameDatas] = useState(null);

	// ##### GAME #####
	const [answers, setAnswers] = useState(null);
	const [score, setScore] = useState(null);

	// ##### INTERFACE #####
	const [hasCheckedTutorial, setHasCheckedTutorial] = useState(false);
	const [currentGameModal, setCurrentGameModal] = useState(null);
	const [isSoundOn, setIsSoundOn] = useState(true);

	// ##### STATUS #####
	const [isTimeRuning, setIsTimeRuning] = useState(false);
	const [isGameComplete, setIsGameComplete] = useState(false);

	// INIT DATAS
	useEffect(() => {
		if (!contextGameDatas) return;
		initAnswers();
	}, [contextGameDatas]);

	function initAnswers() {
		const answersArray = contextGameDatas.gameObjects.map((object, key) => {
			return {
				correctAnswer: object.attrs.behaviourType ? object.attrs.behaviourType : "unsafe",
				userAnswer: null,
				userAnsweredCorrectly: null,
			};
		});
		setAnswers(answersArray);
	}

	function answerQuestion(answerKey, answer) {
		if (!answer || answerKey === null) return;
		const newAnswers = [...answers];
		newAnswers[answerKey].userAnswer = answer;
		newAnswers[answerKey].userAnsweredCorrectly = answer === newAnswers[answerKey].correctAnswer;
		setAnswers(newAnswers);

		const newScore = calculateScore(answers);
		setScore(newScore);
		setCurrentGameModal(<GameAnswerExplanation questionId={answerKey} />);
	}

	function checkIfGameIsComplete() {
		const isGameFinished = answers.every((answer) => answer.userAnswer !== null);
		if (!isGameFinished) return;
		console.warn(answers);
		alert("Game is complete");
		setIsTimeRuning(false);
		setIsGameComplete(true);
	}

	function resetGame() {
		isGameComplete(false);
		setIsTimeRuning(false);
	}

	return (
		<GameContext.Provider
			value={{
				currentGameModal,
				score,
				setCurrentGameModal,
				contextGameDatas,
				setContextGameDatas,
				isTimeRuning,
				setIsTimeRuning,
				isGameComplete,
				answers,
				setAnswers,
				initAnswers,
				isSoundOn,
				setIsSoundOn,
				answerQuestion,
				hasCheckedTutorial,
				setHasCheckedTutorial,
				checkIfGameIsComplete,
			}}>
			{children}
		</GameContext.Provider>
	);
}
