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

import { auth } from "@/auth"
import Link from "@/components/TempDesignSystem/Link"
import { getIntl } from "@/i18n"

import LoginButton from "../LoginButton"

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

import type { TopMenuProps } from "@/types/components/current/header/topMenu"

function capitalize(str: string) {
  return str.charAt(0).toUpperCase().toUpperCase() + str.slice(1).toLowerCase()
}

export default async function TopMenu({
  frontpageLinkText,
  homeHref,
  links,
  languageSwitcher,
  lang,
}: TopMenuProps) {
  const { formatMessage } = await getIntl()
  const session = await auth()
  const user = session ? await serverClient().user.get() : null

  return (
    <div className={styles.topMenu}>
      <div className={styles.container}>
        <a className={styles.homeLink} href={homeHref}>
          {frontpageLinkText}
        </a>

        <ul className={styles.list}>
          {languageSwitcher ? (
            <li className={styles.langSwitcher}>{languageSwitcher}</li>
          ) : null}

          {links.map(({ link }, i) => (
            <li key={link.href + i}>
              <a className={styles.link} href={link.href}>
                {link.title}
              </a>
            </li>
          ))}
          <li className={styles.sessionContainer}>
            {session ? (
              <>
                {user ? (
                  <Link
                    href={logout[lang]}
                    className={styles.sessionLink}
                    prefetch={false}
                  >
                    {capitalize(user.firstName)}
                  </Link>
                ) : null}
                <div className={styles.loginSeparator} />
                <Link
                  href={logout[lang]}
                  className={styles.sessionLink}
                  prefetch={false}
                >
                  {formatMessage({ id: "Log out" })}
                </Link>
              </>
            ) : (
              <LoginButton
                lang={lang}
                className={`${styles.sessionLink} ${styles.loginLink}`}
              />
            )}
          </li>
        </ul>
      </div>
    </div>
  )
}
