import PrimaryButton from "@/components/button/PrimaryButton";
import TextInput from "@/components/input/TextInput";
import DangerMessage from "@/components/message/DangerMessage";
import Pagination from "@/components/pagination/Pagination";
import { useGetGames, useGetGamesCount } from "@/hooks/GameHooks";
import { useEffect, useState } from "react";
import GamesList from "./GamesList";
import GamesListSkeleton from "./GamesListSkeleton";
import GameModal from "./modals/GameModal";


export default function GamesLoader(){
	const [ displayCreateGameModal, setDisplayCreateGameModal ] = useState(false);
	const [ page, setPage ] = useState(1);
	const [ totalPages, setTotalPages ] = useState(1);
	const [ searchTerm, setSearchTerm ] = useState("");
	const pageSize = 10;
	const modalId = crypto.randomUUID().replace("-", "");

	const gamesQuery = useGetGames(page - 1, pageSize);
	const gamesCountQuery = useGetGamesCount();


	useEffect(() => {
		if(gamesCountQuery.status === "success"){
			setTotalPages(Math.ceil(gamesCountQuery.data / pageSize));
		}
	}, [ gamesCountQuery ]);


	if(gamesQuery.status === "pending"){
		return <GamesListSkeleton/>
	}
	else if(gamesQuery.status === "error"){
		return <DangerMessage>Error {gamesQuery.error.message}</DangerMessage>
	}
	else{
		return (
			<>
				<div
					className="flex flex-row justify-between items-center w-full"
				>
					<div
						className="flex flex-row items-center justify-start w-full"
					>
						&nbsp;
					</div>
					{/* Add Game Button */}
					<div
						className="flex flex-row items-center justify-center w-full"
					>
						<PrimaryButton
							className="mb-8"
							onClick={() => setDisplayCreateGameModal(true)}
						>
							Create Game
						</PrimaryButton>
						<GameModal
							display={displayCreateGameModal}
							close={() => setDisplayCreateGameModal(false)}
							game={undefined}
						/>
					</div>
					{/* Game Search Box */}
					<div
						className="flex flex-row items-center justify-end w-full"
					>
						<div>
							<TextInput
								id={`gameSearchBox${modalId}`}
								value={searchTerm}
								onChange={(e) => setSearchTerm(e.target.value)}
								placeholder="Search"
							/>
						</div>
					</div>
				</div>
				{/* Game List */}
				<GamesList
					games={gamesQuery.data ?? []}
				/>
				{/* Pagination */}
				<div
					className="my-12"
				>
					<Pagination
						currentPage={page}
						totalPages={totalPages}
						onChange={setPage}
					/>
				</div>
			</>
		);
	}
}
