import { getCookie } from "cookies-next";
import type { GetServerSideProps } from "next";
import Head from "next/head";
import { Suspense } from "react";
import { Sidebar } from "~/components/area-riservata/sidebar";
import Chat from "~/components/chat/chat";
import { ChatSidebar } from "~/components/chat/chat-sidebar";
import { LoadingPage } from "~/components/loading";
import { SiteHeader } from "~/components/navbar/site-header";
import type { NextPageWithLayout } from "~/pages/_app";
import { useTranslation } from "~/providers/I18nProvider";
import type { ChatsChatid } from "~/schemas/public/Chats";
import type { Session } from "~/server/api/trpc";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";

type ChatPageProps = {
	chatId: ChatsChatid;
	session: Session;
};

/**
 * Pagina di gestione chat per admin: /area-riservata/admin/chats/[chatId]
 */
const ChatPage: NextPageWithLayout<ChatPageProps> = ({
	chatId,
	session,
}: ChatPageProps) => {
	const { t } = useTranslation();
	return (
		<>
			<Head>
				<title>{t.heads.area_riservata_titolo}</title>
				<meta content={t.heads.area_riservata_description} name="description" />
			</Head>

			<div className="h-full flex-1 grow">
				<div className="flex h-full w-full flex-row">
					<div className="h-full">
						<Sidebar
							className="h-full"
							defaultOpen={getCookie("sidebar_minimized") === "true"}
							isAdmin
						/>
					</div>
					<div className="h-full flex-1 grow">
						<div className="flex h-full w-full flex-row">
							<div className="h-full border-r">
								<ChatSidebar chatId={chatId} />
							</div>
							<Suspense fallback={<LoadingPage />}>
								<Chat chatId={chatId} userData={session} />
							</Suspense>
						</div>
					</div>
				</div>
			</div>
		</>
	);
};

ChatPage.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>
	);
};

export const getServerSideProps = (async (context) => {
	const chatId = context.params?.chatId as ChatsChatid;
	if (typeof chatId !== "string")
		return {
			redirect: {
				destination: "/area-riservata/admin/chats/",
				permanent: false,
			},
		};
	const access_token = context.req.cookies.access_token;

	const helper = await TrpcAuthedFetchingIstance({ access_token });
	if (helper) {
		await helper.trpc.messagesSSE.infinite.prefetchInfinite({
			chatId,
		});
		await helper.trpc.chat.getUserInfosByChat.prefetch({
			chatId,
		});
		await helper.trpc.chat.getActiveChats.prefetch();
		await helper.trpc.users.getActiveUsersWithoutChat.prefetch();

		return {
			props: {
				chatId,
				session: helper.session,
				trpcState: helper.trpc.dehydrate(),
			},
		};
	}
	return {
		redirect: {
			destination: "/login",
			permanent: false,
		},
	};
}) satisfies GetServerSideProps<ChatPageProps>;

export default ChatPage;
