import type { Metadata } from "next";
import { cookies } from "next/headers";
import type { ReactNode } from "react";

import authOptions from "@app/api/auth/[...nextauth]/options";
import { Header } from "@components/header";
import { Title } from "@components/title";
import { AppSider } from "@components/sider/AppSider";
import { ThemedLayout } from "@refinedev/mui";
import { getServerSession } from "next-auth/next";
import { redirect } from "next/navigation";

import "../globals.css";

import { META_DATA } from "@config/config";

export const metadata: Metadata = META_DATA;

export default async function MainLayout({
  children,
}: Readonly<{
  children: ReactNode;
}>) {
  const cookieStore = await cookies();
  const theme = cookieStore.get("theme");
  const defaultMode = theme?.value === "dark" ? "dark" : "light";

  const data = await getData();

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

  return (
    <ThemedLayout
      Header={Header}
      Title={Title}
      Sider={AppSider}
      childrenBoxProps={{
        sx: {
          flex: 1,
          minHeight: 0,
          overflow: "auto",
          p: 0,
        },
      }}
      containerBoxProps={{
        sx: { height: "100vh", overflow: "hidden" },
      }}
    >
      {children}
    </ThemedLayout>
  );
}

async function getData() {
  const session = await getServerSession(authOptions);
  return {
    session,
  };
}
