import { Divider } from "@scandic-hotels/design-system/Divider"
import { Typography } from "@scandic-hotels/design-system/Typography"

import { logout } from "@/constants/routes/handleAuth"
import { getProfileSafely } from "@/lib/trpc/memoizedRequests"
import { serverClient } from "@/lib/trpc/server"

import { SASLevelUpgradeCheck } from "@/components/MyPages/SASLevelUpgradeCheck"
import Link from "@/components/TempDesignSystem/Link"
import { getIntl } from "@/i18n"
import { getLang } from "@/i18n/serverContext"
import { getEurobonusMembership } from "@/utils/user"

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

export default async function SidebarMyPages() {
  const intl = await getIntl()
  const profile = await getProfileSafely()
  const eurobonusMembership = profile?.loyalty
    ? getEurobonusMembership(profile.loyalty)
    : null

  return (
    <aside className={styles.sidebar}>
      <nav className={styles.nav}>
        <Typography variant="Title/Subtitle/md">
          <h2 className={styles.title}>
            {intl.formatMessage({
              defaultMessage: "My pages",
            })}
          </h2>
        </Typography>

        <PrimaryLinks />
        <SecondaryLinks />
      </nav>
      {eurobonusMembership && <SASLevelUpgradeCheck />}
    </aside>
  )
}

async function PrimaryLinks() {
  const caller = await serverClient()
  const nav = await caller.navigation.myPages({})

  return (
    <>
      <Divider />
      <ul className={styles.list}>
        {nav?.primaryLinks.map((link) => (
          <li key={link.href}>
            <Link
              href={link.href}
              partialMatch
              prefetch={true}
              size="regular"
              variant="sidebar"
            >
              {link.text}
            </Link>
          </li>
        ))}
      </ul>
    </>
  )
}

async function SecondaryLinks() {
  const lang = await getLang()

  const caller = await serverClient()
  const nav = await caller.navigation.myPages({})
  const intl = await getIntl()

  return (
    <>
      <Divider />
      <ul className={styles.list}>
        {nav?.secondaryLinks.map((link) => (
          <li key={link.href}>
            <Link
              href={link.href}
              partialMatch
              prefetch={true}
              size="small"
              variant="sidebar"
            >
              {link.text}
            </Link>
          </li>
        ))}
        <li>
          <Link
            href={logout[lang]}
            partialMatch
            prefetch={false}
            size="small"
            variant="sidebar"
          >
            {intl.formatMessage({
              defaultMessage: "Log out",
            })}
          </Link>
        </li>
      </ul>
    </>
  )
}
