import AppBar from "@/components/AppBar";
import { getServerSession } from "next-auth";
import { authOptions } 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";

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

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

  if (session) {
    SetupAxiosInterceptors(session?.accessToken);
  }

  return (
    <UploadProvider>
      <CameraProvider>
        <AxiosProvider>
          <>
            <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}>
                <Breadcrumb />
                {children}
              </Stack>
            </Box>
          </>
        </AxiosProvider>
      </CameraProvider>
    </UploadProvider>
  );
}
