import { Fragment } from "react"

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

import Divider from "@/components/TempDesignSystem/Divider"
import Link from "@/components/TempDesignSystem/Link"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import { getIntl } from "@/i18n"

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

import type { LangParams } from "@/types/params"

export default async function Sidebar({ lang }: LangParams) {
  const navigation = await serverClient().contentstack.myPages.navigation.get()
  const { formatMessage } = await getIntl()
  if (!navigation) {
    return null
  }
  return (
    <aside className={styles.sidebar}>
      <nav className={styles.nav}>
        <Subtitle type="two">{navigation.title}</Subtitle>
        {navigation.menuItems.map((menuItem, idx) => (
          <Fragment key={`${menuItem.display_sign_out_link}-${idx}`}>
            <Divider color="beige" />
            <ul className={styles.list}>
              {menuItem.links.map((link) => (
                <li key={link.uid}>
                  <Link
                    color="burgundy"
                    href={link.originalUrl || link.url}
                    partialMatch
                    size={menuItem.display_sign_out_link ? "small" : "regular"}
                    variant="sidebar"
                  >
                    {link.linkText}
                  </Link>
                </li>
              ))}
              {menuItem.display_sign_out_link ? (
                <li>
                  <Link
                    color="burgundy"
                    href={logout[lang]}
                    prefetch={false}
                    size="small"
                    variant="sidebar"
                  >
                    {formatMessage({ id: "Log out" })}
                  </Link>
                </li>
              ) : null}
            </ul>
          </Fragment>
        ))}
      </nav>
    </aside>
  )
}
