import PrimaryButton from "@/components/button/PrimaryButton";
import TextInput from "@/components/input/TextInput";
import Pagination from "@/components/pagination/Pagination";
import { useGetRaidLayoutsByRaidGroupCount } from "@/hooks/RaidLayoutHooks";
import { RaidGroup } from "@/interface/RaidGroup";
import { useEffect, useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import RaidLayoutModal from "./modal/RaidLayoutModal";
import RaidLayoutLoader from "./RaidLayoutLoader";


export default function RaidLayoutTab({
	raidGroup
}:{
	raidGroup: RaidGroup;
}){
	const [ displayCreateRaidLayoutModal, setDisplayCreateRaidLayoutModal ] = useState(false);
	const [ page, setPage ] = useState(1);
	const [ totalPages, setTotalPages ] = useState(1);
	const [ searchTerm, setSearchTerm ] = useState("");
	const [ sentSearchTerm, setSentSearchTerm ] = useState<string>();
	const pageSize = 10;
	const modalId = crypto.randomUUID().replaceAll("-", "");


	const raidLayoutCountQuery = useGetRaidLayoutsByRaidGroupCount(raidGroup.raidGroupId!, sentSearchTerm);


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


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

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


	return (
		<>
			<div
				className="flex flex-row items-center justify-between w-full"
			>
				<div
					className="flex flex-row items-center justify-start w-full"
				>
					&nbsp;
				</div>
				{/* Add Raid Layout Button */}
				<div
					className="flex flex-row items-center justify-center w-full"
				>
					<PrimaryButton
						className="mb-8 text-nowrap"
						onClick={() => setDisplayCreateRaidLayoutModal(true)}
					>
						Create Raid Layout
					</PrimaryButton>
					<RaidLayoutModal
						display={displayCreateRaidLayoutModal}
						close={() => setDisplayCreateRaidLayoutModal(false)}
						raidLayout={undefined}
						raidGroup={raidGroup}
						selectedClassGroups={[]}
					/>
				</div>
				{/* Raid Layout Search Box */}
				<div
					className="flex flex-row items-center justify-end w-full"
				>
					<div>
						<TextInput
							id={`raidLayoutSearchBox${modalId}`}
							value={searchTerm}
							onChange={(e) => setSearchTerm(e.target.value)}
							placeholder="Search"
						/>
					</div>
				</div>
			</div>
			{/* Raid Layout List */}
			<RaidLayoutLoader
				page={page}
				pageSize={pageSize}
				searchTerm={sentSearchTerm}
				raidGroup={raidGroup}
			/>
			{/* Pagination */}
			<div
				className="my-12"
			>
				<Pagination
					currentPage={page}
					totalPages={totalPages}
					onChange={setPage}
				/>
			</div>
		</>
	);
}
