import type { Metadata } from "next";
import { cookies } from "next/headers";
import React, { Suspense } from "react";

import authOptions from "@app/api/auth/[...nextauth]/options";
import { Header } from "@components/header";
import { Title } from "@components/title";
import { MapSkeleton } from "@components/loading/MapSkeleton";
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: React.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" },
      }}
    >
      <Suspense fallback={<MapSkeleton />}>
        {children}
      </Suspense>
    </ThemedLayout>
  );
}

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