import { DeviceCartDrawer } from "@/components/device-cart";
import { Wallet } from "@/components/wallet";
import { NuqsAdapter } from 'nuqs/adapters/next/app'

import { ModeToggle } from "@/components/theme-toggle";
import { AppSidebar } from "@/components/ui/app-sidebar";

import { getProfile } from "@/actions/payment";
import { authOptions } from "@/app/auth";
import { Separator } from "@/components/ui/separator";
import {
	SidebarInset,
	SidebarProvider,
	SidebarTrigger,
} from "@/components/ui/sidebar";
import { tryCatch } from "@/utils/tryCatch";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import { WelcomeBanner } from "../welcome-banner";
import { AccountPopover } from "./account-popver";

export async function ApplicationLayout({
	children,
}: { children: React.ReactNode }) {
	const session = await getServerSession(authOptions);

	if (!session) return redirect("/auth/signin");
	const [userError, userProfile] = await tryCatch(getProfile());
	if (userError) {
		if (userError.message === "Invalid token.") redirect("/auth/signin");
		return null;
	}
	return (
		<SidebarProvider>
			<AppSidebar />
			<SidebarInset>
				<header className="flex justify-between sticky top-0 bg-background h-16 shrink-0 items-center gap-2 border-b px-4 z-10">
					<div className="flex items-center gap-2 ">
						<SidebarTrigger className="-ml-1" />
						<Separator orientation="vertical" className="mr-2 h-4" />
					</div>

					<div className="flex items-center gap-2">
						<Wallet walletBalance={userProfile?.wallet_balance || 0} />
						<ModeToggle />
						<AccountPopover />
					</div>
				</header>
				<WelcomeBanner
					firstName={session?.user?.first_name}
					lastName={session?.user?.last_name}
				/>
				<DeviceCartDrawer />
				<div className="p-4 flex flex-col flex-1 rounded-lg bg-background">
					<NuqsAdapter>
						{children}
					</NuqsAdapter>
				</div>
			</SidebarInset>
		</SidebarProvider>
	);
}
