import { MembershipLevelEnum } from "@/constants/membershipLevels"
import { getMembershipLevelSafely, getName } from "@/lib/trpc/memoizedRequests"
import { serverClient } from "@/lib/trpc/server"

import LoginButton from "@/components/LoginButton"
import {
  getPrimaryLinks,
  getSecondaryLinks,
} from "@/components/MyPages/menuItems"
import { getIntl } from "@/i18n"
import { getLang } from "@/i18n/serverContext"

import Avatar from "../Avatar"
import MyPagesMenu, { MyPagesMenuSkeleton } from "../MyPagesMenu"
import MyPagesMobileMenu, {
  MyPagesMobileMenuSkeleton,
} from "../MyPagesMobileMenu"

import styles from "./myPagesMenuWrapper.module.css"

export default async function MyPagesMenuWrapper() {
  const lang = getLang()
  const [intl, user, membership, primaryLinks, secondaryLinks] =
    await Promise.all([
      getIntl(),
      getName(),
      getMembershipLevelSafely(),
      getPrimaryLinks({ lang }),
      getSecondaryLinks({ lang }),
    ])

  const membershipLevel = membership?.membershipLevel
    ? await serverClient().contentstack.loyaltyLevels.byLevel({
        level: MembershipLevelEnum[membership.membershipLevel],
      })
    : null

  return (
    <>
      {user ? (
        <>
          <MyPagesMenu
            membershipLevel={membershipLevel}
            membership={membership}
            primaryLinks={primaryLinks}
            secondaryLinks={secondaryLinks}
            user={user}
          />
          <MyPagesMobileMenu
            membershipLevel={membershipLevel}
            membership={membership}
            primaryLinks={primaryLinks}
            secondaryLinks={secondaryLinks}
            user={user}
          />
        </>
      ) : (
        <LoginButton
          className={styles.loginLink}
          aria-label={intl.formatMessage({ id: "Log in/Join" })}
          position="top menu"
          trackingId="loginStartNewTopMenu"
        >
          <Avatar />
          <span className={styles.loginText}>
            {intl.formatMessage({ id: "Log in/Join" })}
          </span>
        </LoginButton>
      )}
    </>
  )
}

export function MyPagesMenuWrapperSkeleton() {
  return (
    <div>
      <MyPagesMenuSkeleton />
      <MyPagesMobileMenuSkeleton />
    </div>
  )
}
