"use client"

import { Dialog, Modal } from "react-aria-components"
import { useIntl } from "react-intl"

import useDropdownStore from "@/stores/main-menu"

import { useHandleKeyUp } from "@/hooks/useHandleKeyUp"
import { getInitials } from "@/utils/user"

import Avatar from "../Avatar"
import MainMenuButton from "../MainMenuButton"
import MyPagesMenuContent from "../MyPagesMenuContent"

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

import type { MyPagesMenuProps } from "@/types/components/header/myPagesMenu"

export default function MyPagesMobileMenu({
  membership,
  navigation,
  user,
}: MyPagesMenuProps) {
  const intl = useIntl()
  const { toggleMyPagesMobileMenu, isMyPagesMobileMenuOpen } =
    useDropdownStore()

  useHandleKeyUp((event: KeyboardEvent) => {
    if (event.key === "Escape" && isMyPagesMobileMenuOpen) {
      toggleMyPagesMobileMenu()
    }
  })

  return (
    <div className={styles.myPagesMobileMenu}>
      <MainMenuButton
        className={styles.button}
        onClick={toggleMyPagesMobileMenu}
        aria-label={intl.formatMessage({ id: "Open my pages menu" })}
      >
        <Avatar initials={getInitials(user.firstName, user.lastName)} />
      </MainMenuButton>
      <Modal className={styles.modal} isOpen={isMyPagesMobileMenuOpen}>
        <Dialog
          className={styles.dialog}
          aria-label={intl.formatMessage({ id: "My pages menu" })}
        >
          <MyPagesMenuContent
            membership={membership}
            navigation={navigation}
            user={user}
            toggleOpenStateFn={toggleMyPagesMobileMenu}
          />
        </Dialog>
      </Modal>
    </div>
  )
}
