
import { Type, User } from "@/interfaces/user";
import {sessionOptions} from "@/lib/session";
import useFilterStore from "@/stores/listFilterStore";
import { redirect, serialize } from "@/utils";
import { requestUser } from "@/utils/api";
import { shouldRedirectHome } from "@/utils/navigation.disabled";
import {withIronSessionSsr} from "iron-session/next";
import Head from "next/head";
import {useRouter} from "next/router";
import { BsChevronLeft} from "react-icons/bs";
import {ToastContainer} from "react-toastify";
import UserList from "../(admin)/Lists/UserList";

export const getServerSideProps = withIronSessionSsr(async ({req, res, query}) => {
	const user = await requestUser(req, res)
	if (!user) return redirect("/login")

	if (shouldRedirectHome(user)) return redirect("/")

	const {type} = query as {type?: Type}

	return {
		props: serialize({user, type}),
	};
}, sessionOptions);

interface Props {
	user: User
	type?: Type
}

export default function UsersListPage({ user, type }: Props) {
	const [filters, clearFilters] = useFilterStore((state) => [state.userFilters, state.clearUserFilters]);

	const router = useRouter()

	return (
		<>
			<Head>
				<title>EnCoach</title>
				<meta
					name="description"
					content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
				/>
				<meta name="viewport" content="width=device-width, initial-scale=1" />
				<link rel="icon" href="/favicon.ico" />
			</Head>
			<ToastContainer />

				<>
					<UserList
						user={user}
						type={type}
						filters={filters.map((f) => f.filter)}
						renderHeader={(total) => (
							<div className="flex items-center gap-2">
								<button
									onClick={() => {
										clearFilters()
										router.back()
									}}
									className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
									<BsChevronLeft />
								</button>
								<h2 className="font-bold text-2xl">Users ({ total })</h2>
							</div>
						)}
					/>
				</>
		</>
	);
}
