import DangerMessage from "@/components/message/DangerMessage";
import TabGroup, { Tab } from "@/components/tab/TabGroup";
import TutorialComponent from "@/components/TutorialComponent";
import { useGetGame } from "@/hooks/GameHooks";
import { TutorialStatus } from "@/interface/AccountTutorialStatus";
import { Game } from "@/interface/Game";
import { useAuth } from "@/providers/AuthProvider";
import GameCalendarDisplay from "@/ui/calendar/GameCalendarDisplay";
import GameHeader from "@/ui/game/GameHeader";
import GameClassDisplay from "@/ui/gameClass/GameClassDisplay";
import RaidGroupsByGameDisplay from "@/ui/raidGroup/RaidGroupsByGameDisplay";
import { gameTutorialSteps } from "@/util/TutorialUtil";
import { useEffect, useState } from "react";
import { Navigate, useParams } from "react-router";


export default function GamePage(){
	const { gameId } = useParams();
	const [ game, setGame ] = useState<Game>();
	const { tutorialsStatus, setTutorialsStatus } = useAuth();

	const gameQuery = useGetGame(gameId ?? "", false);


	const updateGameTutorialStatus = () => {
		const newTutorialsStatus = { ...tutorialsStatus };
		if(tutorialsStatus.gameTutorialStatus === TutorialStatus.COMPLETED){
			newTutorialsStatus.gameTutorialStatus = TutorialStatus.NOT_COMPLETED;
		}
		else if(tutorialsStatus.gameTutorialStatus === TutorialStatus.NOT_COMPLETED){
			newTutorialsStatus.gameTutorialStatus = TutorialStatus.COMPLETED;
		}
		setTutorialsStatus(newTutorialsStatus);
	}


	useEffect(() => {
		if(gameQuery.status === "success"){
			setGame(gameQuery.data);
		}
	}, [ gameQuery ]);


	if(gameQuery.status === "pending"){
		return (
			<div>Loading...</div>
		);
	}
	else if(gameQuery.status === "error"){
		return (
			<DangerMessage>Error: {gameQuery.error.message}</DangerMessage>
		);
	}
	else if(gameQuery.status === "success" && gameQuery.data === undefined){
		return (
			<Navigate to="/game"/>
		);
	}
	else if(game){
		const tabs: Tab[] = [
			{
				tabId: "calendarTab",
				tabHeader: "Calendar",
				tabContent: <GameCalendarDisplay gameId={gameId!}/>
			},
			{
				tabId: "raidGroupsTab",
				tabHeader: "Raid Groups",
				tabContent: <RaidGroupsByGameDisplay gameId={gameId!}/>
			},
			{
				tabId: "gameClassesTab",
				tabHeader: "Classes",
				tabContent: <GameClassDisplay gameId={gameId!}/>
			}
		];


		return (
			<main
				className="flex flex-col items-center justify-center"
			>
				{/* Tutorials */}
				{
					tutorialsStatus.gameTutorialStatus === TutorialStatus.NOT_COMPLETED &&
					<TutorialComponent
						steps={gameTutorialSteps}
						run={tutorialsStatus.gameTutorialStatus === TutorialStatus.NOT_COMPLETED}
						showProgress={true}
						showSkipButton={true}
						continuous={true}
						disableScrolling={true}
						updateFunction={updateGameTutorialStatus}
					/>
				}
				<GameHeader
					game={game}
				/>
				<TabGroup
					tabs={tabs}
				/>
			</main>
		);
	}
}
