import { use } from 'react';

import { cookies } from 'next/headers';

import { Page, PageMobileNavigation, PageNavigation } from '@kit/ui/page';
import { SidebarProvider } from '@kit/ui/shadcn-sidebar';

import { AdminSidebar } from '~/admin/_components/admin-sidebar';
import { AdminMenuNavigation } from '~/admin/_components/admin-menu-navigation';
import { AdminMobileNavigation } from '~/admin/_components/mobile-navigation';

import { loadUserWorkspace } from '../home/(user)/_lib/server/load-user-workspace';

export const metadata = {
  title: `Super Admin`,
};

export const dynamic = 'force-dynamic';

export default function AdminLayout(props: React.PropsWithChildren) {
  const state = use(getLayoutState());
  const workspace = use(loadUserWorkspace());

  return (
    <Page style={'header'}>
      <PageNavigation>
        <AdminMenuNavigation workspace={workspace} />
      </PageNavigation>

      <PageMobileNavigation>
        <AdminMobileNavigation />
      </PageMobileNavigation>

      <SidebarProvider defaultOpen={state.open}>
        <Page style={'sidebar'}>
          <PageNavigation>
            <AdminSidebar />
          </PageNavigation>
          {props.children}
        </Page>
      </SidebarProvider>
    </Page>
  );
}

async function getLayoutState() {
  const cookieStore = await cookies();
  const sidebarOpenCookie = cookieStore.get('sidebar:state');

  return {
    open: sidebarOpenCookie?.value !== 'true',
  };
}
