import type { QueryClient } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import {
	createRootRouteWithContext,
	Outlet,
	useRouter,
} from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
import mobile from "is-mobile";
import { useEffect } from "react";
import { Toaster } from "sonner";
import { userAccess } from "../lib/authClient";
import { SessionGuard } from "../lib/providers/SessionProvider";
import { ThemeProvider } from "../lib/providers/theme-provider";
import { coreSocket } from "../lib/socket.io/socket";

interface RootRouteContext {
	queryClient: QueryClient;
	//user: User | null;
	//login: (user: User) => void;
	//logout: () => void;
}

const RootLayout = () => {
	//const { logout, login } = Route.useRouteContext();

	const router = useRouter();
	// console.log(mobile({ featureDetect: true, tablet: true }));

	// if mobile lets move to the mobile section.
	useEffect(() => {
		if (mobile({ featureDetect: true, tablet: true })) {
			router.navigate({ to: "/m" });
		}

		coreSocket.on("connect", () => {
			console.log("✅ Connected:", coreSocket.id);
		});

		coreSocket.on("disconnect", () => {
			console.log("🔴 Disconnected");
		});

		return () => {
			coreSocket.off("connect");
			coreSocket.off("disconnect");
		};
	}, []);

	return (
		<div>
			<SessionGuard>
				<ThemeProvider>
					<div className="flex-2 overflow-y-auto">
						<Outlet />
					</div>
					<Toaster expand richColors closeButton />
					{userAccess(null, ["systemAdmin"]) && (
						<div className="flex flex-row">
							<TanStackRouterDevtools position="bottom-right" />
							<ReactQueryDevtools
								initialIsOpen={false}
								buttonPosition="bottom-right"
							/>
						</div>
					)}
				</ThemeProvider>
			</SessionGuard>
		</div>
	);
};

export const Route = createRootRouteWithContext<RootRouteContext>()({
	component: RootLayout,
});
