"use client"
import { Fragment } from "react"
import { useIntl } from "react-intl"

import { Lang } from "@/constants/languages"
import { logout } from "@/constants/routes/handleAuth"
import { navigationQueryRouter } from "@/server/routers/contentstack/myPages/navigation/query"
import useDropdownStore from "@/stores/main-menu"

import Divider from "@/components/TempDesignSystem/Divider"
import Link from "@/components/TempDesignSystem/Link"
import Title from "@/components/TempDesignSystem/Text/Title"

import styles from "./my-pages-mobile-dropdown.module.css"

type Navigation = Awaited<ReturnType<(typeof navigationQueryRouter)["get"]>>

export default function MyPagesMobileDropdown({
  navigation,
  lang,
}: {
  navigation: Navigation
  lang: Lang | null
}) {
  const { formatMessage } = useIntl()
  const { toggleMyPagesMobileMenu, isMyPagesMobileMenuOpen } =
    useDropdownStore()

  if (!navigation) {
    return null
  }

  return (
    <nav
      className={`${styles.navigationMenu} ${isMyPagesMobileMenuOpen ? styles.navigationMenuIsOpen : ""}`}
    >
      <Title className={styles.heading} textTransform="capitalize" level="h5">
        {navigation.title}
      </Title>
      {navigation.menuItems.map((menuItem, idx) => (
        <Fragment key={`${menuItem.display_sign_out_link}-${idx}`}>
          <div className={styles.dividerWrapper}>
            <Divider color="subtle" />
          </div>
          <ul className={styles.dropdownWrapper}>
            <ul className={styles.dropdownLinks}>
              {menuItem.links.map((link) => (
                <li key={link.uid}>
                  <Link
                    href={link.originalUrl || link.url}
                    partialMatch
                    size={menuItem.display_sign_out_link ? "small" : "regular"}
                    variant="myPageMobileDropdown"
                    color="burgundy"
                    onClick={toggleMyPagesMobileMenu}
                  >
                    {link.linkText}
                  </Link>
                </li>
              ))}
              {menuItem.display_sign_out_link && lang ? (
                <li>
                  <Link
                    href={logout[lang]}
                    prefetch={false}
                    size="small"
                    color="burgundy"
                    variant="myPageMobileDropdown"
                  >
                    {formatMessage({ id: "Log out" })}
                  </Link>
                </li>
              ) : null}
            </ul>
          </ul>
        </Fragment>
      ))}
    </nav>
  )
}
