"use client"

import { useEffect } from "react"
import { Dialog, Modal } from "react-aria-components"
import { useIntl } from "react-intl"
import { useMediaQuery } from "usehooks-ts"

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 { DropdownTypeEnum } from "@/types/components/dropdown/dropdown"
import type { MyPagesMenuProps } from "@/types/components/header/myPagesMenu"

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

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

  const isAboveMobile = useMediaQuery("(min-width: 768px)")
  useEffect(() => {
    if (isAboveMobile && isMyPagesMobileMenuOpen) {
      toggleDropdown(DropdownTypeEnum.MyPagesMobileMenu)
    }
  }, [isAboveMobile, isMyPagesMobileMenuOpen, toggleDropdown])

  // Making sure the menu is always opened at the top of the page, just below the header.
  useEffect(() => {
    if (isMyPagesMobileMenuOpen) {
      window.scrollTo({ top: 0, behavior: "instant" })
    }
  }, [isMyPagesMobileMenuOpen])

  return (
    <div className={styles.myPagesMobileMenu}>
      <MainMenuButton
        className={styles.button}
        onClick={() => toggleDropdown(DropdownTypeEnum.MyPagesMobileMenu)}
        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
            membershipLevel={membershipLevel}
            membership={membership}
            navigation={navigation}
            user={user}
            toggleOpenStateFn={() =>
              toggleDropdown(DropdownTypeEnum.MyPagesMobileMenu)
            }
          />
        </Dialog>
      </Modal>
    </div>
  )
}

export function MyPagesMobileMenuSkeleton() {
  return (
    <div className={styles.myPagesMobileMenu}>
      <MainMenuButton className={styles.button}>
        <Avatar />
      </MainMenuButton>
    </div>
  )
}
