import AppBar from "@/components/AppBar";
import { AuthOptions, getServerSession } from "next-auth";
import { authOptions, SessionWithTokens } from "@/config/authConfig";
import { redirect } from "next/navigation";
import Box from "@mui/material/Box";
import { NAVIGATION_CONTENT_WIDTH } from "@/config/uiConfig";
import Stack from "@mui/material/Stack";
import Breadcrumb from "@/components/Breadcrumb";
import { AxiosProvider } from "@/app/(main)/axios/AxiosProvider";
import { SetupAxiosInterceptors } from "@/app/(main)/axios/axiosInstance";
import { CameraProvider } from "@/components/Cameras/CameraProvider";
import { UploadProvider } from "@/components/UploadProvider/UploadProvider";
import SessionProviderWrapper from "@/components/SessionProviderWrapper/SessionProviderWrapper";
import QrCodeScannerProvider from "@/components/QrCodeScannerProvider/QrCodeScannerProvider";
import { I18nProvider } from "@/i18n";

export default async function MainLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await getServerSession<AuthOptions, SessionWithTokens>(authOptions);

  if (!session?.user) {
    redirect("/login");
  }

  // console.log(session?.user);

  // Verify if the session is valid
  if (session) {
    SetupAxiosInterceptors(session.accessToken);
  }

  return (
    <SessionProviderWrapper session={session}>
    <UploadProvider>
      <CameraProvider>
        <AxiosProvider>
          <QrCodeScannerProvider>
            <>
              <AppBar
                profileName={session.user.name!}
                avatarImageSrc={session.user.image || undefined}
              />
              <Box
                component="main"
                sx={{
                  marginInlineStart: { xs: 0, xl: NAVIGATION_CONTENT_WIDTH },
                  padding: { xs: "1rem", sm: "1.5rem", lg: "3rem" },
                }}
              >
                <Stack spacing={2}>
                  <I18nProvider namespaces={["common"]}>
                    <Breadcrumb />
                  </I18nProvider>
                  {children}
                </Stack>
              </Box>
            </>
          </QrCodeScannerProvider>
        </AxiosProvider>
      </CameraProvider>
      </UploadProvider>
    </SessionProviderWrapper>
  );
}
