import React, { useEffect, useState } from "react";
import GameObjects from "./GameObjects";
import { useGame } from "../../hooks/useGame";
import { postWordpressStatisticsData, useWordpressCustomData } from "../../services/WordpressFetchData.js";
import Score from "../../components/game/Score.jsx";
import Timer from "../../components/game/Timer.jsx";
import Help from "../../components/game/Help.jsx";
import SoundControl from "../../components/game/SoundControl.jsx";
import ExtraControls from "../../components/game/ExtraControls.jsx";
import { useUser } from "../../hooks/useUser.jsx";

export default function GameContainer({ gameId }) {
	const gameDatas = useWordpressCustomData(`/screen/play/${gameId}`);
	console.log(gameDatas);

	const [currentTime, setCurrentTime] = useState(0);
	const [isDragging, setIsDragging] = useState(false);
	const [startX, setStartX] = useState(0);

	const { answers, contextGameDatas, setContextGameDatas, isGameComplete, score } = useGame();
	const { language, country } = useUser();

	useEffect(() => {
		if (!gameDatas) return;
		setContextGameDatas(gameDatas);
	}, [gameDatas]);

	useEffect(() => {
		if (!isGameComplete) return;
		// console.log(contextGameDatas);
		// const datas = {
		// 	user_locale: language,
		// 	user_country: country,
		// 	level_post_id: contextGameDatas.gameId,
		// 	level_score: score,
		// 	level_completion_time: currentTime,
		// };
		// postWordpressStatisticsData(datas);
		console.log("##############");
		// console.log(datas);
		console.log("##############");
	}, [isGameComplete]);

	// HANDLE CANVAS DRAGGING INTERACTIONS
	function handleMouseDown(e) {
		const container = document.querySelector(".lhoist-blocks-search-and-find");
		setIsDragging(true);
		setStartX(e.clientX + container.scrollLeft);
	}

	function handleMouseMove(e) {
		if (!isDragging) return;
		const container = document.querySelector(".lhoist-blocks-search-and-find");
		const newScrollLeft = startX - e.clientX;
		container.scrollLeft = newScrollLeft;
	}

	function handleMouseUp() {
		setIsDragging(false);
	}

	if (!contextGameDatas) return;

	const gameBackgroundUrl = contextGameDatas.gameBlockDatas.attrs.coverUrl;
	const blocks = contextGameDatas.gameBlockDatas.innerBlocks;

	return (
		<>
			<ExtraControls />
			<SoundControl />
			<Score />
			<Timer currentTime={currentTime} setCurrentTime={setCurrentTime} />
			<Help />
			<div onMouseDown={handleMouseDown} onMouseMove={handleMouseMove} onMouseUp={handleMouseUp}>
				<section className='wp-block-lhoist-blocks-search-and-find lhoist-blocks-search-and-find'>
					<div className='lhoist-blocks-search-and-find__objects-container'>
						<img
							className='lhoist-blocks-search-and-find__background_picture'
							src={gameBackgroundUrl}
							alt={""}
						/>
						<GameObjects blocks={blocks} />
					</div>
				</section>
			</div>
		</>
	);
}
