import PrimaryButton from "@/components/button/PrimaryButton";
import TextInput from "@/components/input/TextInput";
import Pagination from "@/components/pagination/Pagination";
import { useGetGamesCount } from "@/hooks/GameHooks";
import { useEffect, useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import { GamesLoader } from "./GamesLoader";
import GameModal from "./modals/GameModal";


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

	const gamesCountQuery = useGetGamesCount(sentSearchTerm);


	const updateSearchTerm = useDebouncedCallback((newSearchTerm: string) => {
		setSentSearchTerm(newSearchTerm.length ? newSearchTerm : undefined);
	}, 1000);


	useEffect(() => {
		updateSearchTerm(searchTerm ?? "");
	}, [ searchTerm, updateSearchTerm ]);


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


	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 */}
			<GamesLoader
				page={page}
				pageSize={pageSize}
				searchTerm={sentSearchTerm}
			/>
			{/* Pagination */}
			<div
				className="my-12"
			>
				<Pagination
					currentPage={page}
					totalPages={totalPages}
					onChange={setPage}
				/>
			</div>
		</>
	);
}
