import { getCookie } from "cookies-next";
import type { GetServerSideProps } from "next";
import Head from "next/head";
import { Sidebar } from "~/components/area-riservata/sidebar";
import { ChatSidebar } from "~/components/chat/chat-sidebar";
import { LoadingPage } from "~/components/loading";
import { SiteHeader } from "~/components/navbar/site-header";
import { Status500 } from "~/components/status-page";
import type { NextPageWithLayout } from "~/pages/_app";
import { useSession } from "~/providers/SessionProvider";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { api } from "~/utils/api";

/**
 * Pagina di gestione chat per admin: /area-riservata/admin/chats
 */
const AdminChats: NextPageWithLayout = () => {
	const { status } = useSession();

	const { data: activeChats, isLoading: isLoadingActiveChats } =
		api.chat.getActiveChats.useQuery();

	const { data: inactiveUsers, isLoading: isLoadingInactiveUsers } =
		api.users.getActiveUsersWithoutChat.useQuery();

	if (status === "LOADING" || isLoadingActiveChats || isLoadingInactiveUsers)
		return <LoadingPage />;

	if (status !== "AUTHENTICATED") {
		window.location.reload();
		return <LoadingPage />;
	}
	if (!activeChats || !inactiveUsers) return <Status500 />;

	return (
		<>
			<Head>
				<title>Chat - Infoalloggi.it</title>
			</Head>
			<div className="flex h-full w-full flex-col md:flex-row">
				<Sidebar
					defaultOpen={getCookie("sidebar_minimized") === "true"}
					isAdmin
				/>

				<div className="h-full flex-1 grow">
					<div className="flex h-full w-full flex-row">
						<div className="h-full border-r">
							<ChatSidebar chatId={null} />
						</div>
						<div className="w-full" />
					</div>
				</div>
			</div>
		</>
	);
};
export default AdminChats;

export const getServerSideProps = (async (context) => {
	const access_token = context.req.cookies.access_token;

	const helpers = await TrpcAuthedFetchingIstance({ access_token });
	if (helpers) {
		await helpers.trpc.chat.getActiveChats.prefetch();
		await helpers.trpc.users.getActiveUsersWithoutChat.prefetch();
		return {
			props: {
				trpcState: helpers.trpc.dehydrate(),
			},
		};
	}
	return {
		props: {},
	};
}) satisfies GetServerSideProps;

AdminChats.getLayout = function getLayout(page) {
	return (
		<div className="h-screen">
			<div className="flex h-full flex-col">
				<SiteHeader />
				<div className="flex min-h-0 grow">{page}</div>
			</div>
		</div>
	);
};
