"use client"

import { useSession } from "next-auth/react"
import { useIntl } from "react-intl"

import { MembershipLevelEnum } from "@/constants/membershipLevels"
import { trpc } from "@/lib/trpc/client"

import LoginButton from "@/components/LoginButton"
import useLang from "@/hooks/useLang"
import { isValidClientSession } from "@/utils/clientSession"

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

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

export default function MyPagesMenuWrapper() {
  const intl = useIntl()
  const lang = useLang()

  const { data: session } = useSession()
  const isUserLoggedIn = isValidClientSession(session)

  const { data: user, isLoading: isLoadingUser } = trpc.user.name.useQuery()
  const { data: membership, isLoading: isLoadingMembership } =
    trpc.user.safeMembershipLevel.useQuery()

  const { data: membershipLevel, isLoading: isLoadingMembershipLevel } =
    trpc.contentstack.loyaltyLevels.byLevel.useQuery(
      {
        lang: lang,
        level: MembershipLevelEnum[membership?.membershipLevel ?? "L1"],
      },
      {
        enabled: !!membership?.membershipLevel,
      }
    )

  if (isLoadingUser || isLoadingMembership || isLoadingMembershipLevel) {
    return <MyPagesMenuWrapperSkeleton />
  }

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

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