"use client"

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

import { MembershipLevelEnum } from "@scandic-hotels/common/constants/membershipLevels"
import { useLazyPathname } from "@scandic-hotels/common/hooks/useLazyPathname"
import { Avatar } from "@scandic-hotels/design-system/Avatar"
import { LoginButton } from "@scandic-hotels/design-system/LoginButton"
import { trpc } from "@scandic-hotels/trpc/client"
import { isValidSession } from "@scandic-hotels/trpc/utils/session"

import useLang from "@/hooks/useLang"
import { trackLoginClick } from "@/utils/tracking"

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 loginPathname = useLazyPathname({ includeSearchParams: true })

  const { data: session, status } = useSession()
  const isSessionLoading = status === "loading"
  const isUserLoggedIn = isValidSession(session)

  const { data: user, isLoading: isLoadingUser } = trpc.user.name.useQuery(
    undefined,
    {
      refetchOnWindowFocus: true,
      refetchInterval: 300_000,
      refetchOnReconnect: "always",
      enabled: isUserLoggedIn,
    }
  )
  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: isUserLoggedIn && !!membership?.membershipLevel,
      }
    )

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

  return (
    <>
      {isUserLoggedIn && user ? (
        <>
          <MyPagesMenu
            membershipLevel={membershipLevel ?? null}
            membership={membership}
            user={user}
          />
          <MyPagesMobileMenu
            membershipLevel={membershipLevel ?? null}
            membership={membership}
            user={user}
          />
        </>
      ) : (
        <LoginButton
          aria-label={intl.formatMessage({
            id: "header.logInJoin",
            defaultMessage: "Log in/Join",
          })}
          className={styles.loginLink}
          lang={lang}
          onClick={() => {
            trackLoginClick("top menu")
          }}
          redirectTo={loginPathname}
          loginPosition="top-menu"
          variant="Text"
          wrapping={false}
        >
          <Avatar />
          <span className={styles.loginText}>
            {intl.formatMessage({
              id: "header.logInJoin",
              defaultMessage: "Log in/Join",
            })}
          </span>
        </LoginButton>
      )}
    </>
  )
}

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