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

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 useLang from "@/hooks/useLang"

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

import { DropdownTypeEnum } from "@/types/components/dropdown/dropdown"

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

export default function MyPagesMobileDropdown({
  navigation,
}: {
  navigation: Navigation
}) {
  const intl = useIntl()
  const lang = useLang()
  const { toggleDropdown, 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={() =>
                      toggleDropdown(DropdownTypeEnum.MyPagesMobileMenu)
                    }
                  >
                    {link.linkText}
                  </Link>
                </li>
              ))}
              {menuItem.display_sign_out_link && lang ? (
                <li>
                  <Link
                    href={logout[lang]}
                    prefetch={false}
                    size="small"
                    color="burgundy"
                    variant="myPageMobileDropdown"
                  >
                    {intl.formatMessage({ id: "Log out" })}
                  </Link>
                </li>
              ) : null}
            </ul>
          </ul>
        </Fragment>
      ))}
    </nav>
  )
}
