import { use } from 'react';

import { retrieveCart } from '@lib/data/cart';
import { StoreCart } from '@medusajs/types';

import { UserWorkspaceContextProvider } from '@kit/accounts/components';
import { AppLogo } from '@kit/shared/components/app-logo';
import { pathsConfig } from '@kit/shared/config';
import { Page, PageMobileNavigation, PageNavigation } from '@kit/ui/page';
import { SidebarProvider } from '@kit/ui/shadcn-sidebar';

import { withI18n } from '~/lib/i18n/with-i18n';

// home imports
import { HomeMenuNavigation } from '../_components/home-menu-navigation';
import { loadUserWorkspace } from '../_lib/server/load-user-workspace';
import { SettingsMobileNavigation } from './_components/settings-navigation';
import { SettingsSidebar } from './_components/settings-sidebar';

function UserSettingsLayout({ children }: React.PropsWithChildren) {
  return <HeaderLayout>{children}</HeaderLayout>;
}

export default withI18n(UserSettingsLayout);

function HeaderLayout({ children }: React.PropsWithChildren) {
  const workspace = use(loadUserWorkspace());
  const cart = use(retrieveCart());

  return (
    <UserWorkspaceContextProvider value={workspace}>
      <Page style={'header'}>
        <PageNavigation>
          <HomeMenuNavigation workspace={workspace} cart={cart} />
        </PageNavigation>

        <PageMobileNavigation className={'flex items-center justify-between'}>
          <MobileNavigation workspace={workspace} cart={cart} />
        </PageMobileNavigation>

        <SidebarProvider defaultOpen>
          <Page style={'sidebar'}>
            <PageNavigation>
              <SettingsSidebar />
            </PageNavigation>
            <div className="min-h-full min-w-full md:mt-28">{children}</div>
          </Page>
        </SidebarProvider>
      </Page>
    </UserWorkspaceContextProvider>
  );
}

function MobileNavigation({
  workspace,
  cart,
}: {
  workspace: Awaited<ReturnType<typeof loadUserWorkspace>>;
  cart: StoreCart | null;
}) {
  return (
    <>
      <AppLogo href={pathsConfig.app.home} />

      <SettingsMobileNavigation workspace={workspace} cart={cart} />
    </>
  );
}
