"use client"

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

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

import { GiftIcon, SearchIcon, ServiceIcon } from "@/components/Icons"
import LanguageSwitcher from "@/components/LanguageSwitcher"
import { useHandleKeyUp } from "@/hooks/useHandleKeyUp"

import HeaderLink from "../../HeaderLink"
import NavigationMenu from "../NavigationMenu"

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

import type { MobileMenuProps } from "@/types/components/header/mobileMenu"

export default function MobileMenu({
  menuItems,
  languageUrls,
  topLink,
}: MobileMenuProps) {
  const intl = useIntl()
  const {
    isHamburgerMenuOpen,
    isMyPagesMobileMenuOpen,
    isLanguageSwitcherOpen,
    toggleHamburgerMenu,
    toggleMyPagesMobileMenu,
    toggleLanguageSwitcher,
  } = useDropdownStore()

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

  function handleHamburgerClick() {
    if (isMyPagesMobileMenuOpen) {
      toggleMyPagesMobileMenu()
    } else {
      if (isLanguageSwitcherOpen) {
        toggleLanguageSwitcher()
      }

      toggleHamburgerMenu()
    }
  }

  return (
    <>
      <button
        type="button"
        className={`${styles.hamburger} ${isHamburgerMenuOpen || isMyPagesMobileMenuOpen ? styles.isExpanded : ""}`}
        aria-label={intl.formatMessage({
          id: isHamburgerMenuOpen ? "Close menu" : "Open menu",
        })}
        onClick={handleHamburgerClick}
      >
        <span className={styles.bar}></span>
      </button>
      <Modal className={styles.modal} isOpen={isHamburgerMenuOpen}>
        <Dialog
          className={styles.dialog}
          aria-label={intl.formatMessage({ id: "Menu" })}
        >
          <NavigationMenu isMobile={true} items={menuItems} />
          <footer className={styles.footer}>
            <HeaderLink href="#">
              <SearchIcon width={20} height={20} color="burgundy" />
              {intl.formatMessage({ id: "Find booking" })}
            </HeaderLink>
            {topLink ? (
              <HeaderLink href={topLink.href}>
                <GiftIcon width={20} height={20} color="burgundy" />
                {topLink.title}
              </HeaderLink>
            ) : null}
            <HeaderLink href="#">
              <ServiceIcon width={20} height={20} color="burgundy" />
              {intl.formatMessage({ id: "Customer service" })}
            </HeaderLink>
            <LanguageSwitcher type="mobileHeader" urls={languageUrls} />
          </footer>
        </Dialog>
      </Modal>
    </>
  )
}
