"use client"

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

import { Button } from "@scandic-hotels/design-system/Button"

import { UserMenu } from "../UserMenu"

import styles from "./mobile-menu.module.css"

export function MobileMenu({ children }: React.PropsWithChildren) {
  const intl = useIntl()
  const [state, setState] = useState<"nav" | "user" | "closed">("closed")

  const closeMsg = intl.formatMessage({
    id: "header.closeMenu",
    defaultMessage: "Close menu",
  })
  const openMsg = intl.formatMessage({
    id: "header.openMenu",
    defaultMessage: "Open menu",
  })

  const isOpen = state !== "closed"
  return (
    <div className={styles.mobileMenu}>
      <UserMenu
        isMobile={true}
        isOpen={state === "user"}
        onOpenChange={(open) => {
          setState(open ? "user" : "closed")
        }}
      />
      <div id="close-menu-container" style={{ position: "relative" }}>
        <Button
          variant={"Text"}
          type="button"
          className={`${styles.hamburger} ${isOpen ? styles.isExpanded : ""}`}
          aria-label={isOpen ? closeMsg : openMsg}
          onPress={() => {
            window.scrollTo(0, 0)
            setState(isOpen ? "closed" : "nav")
          }}
        >
          <span className={styles.bar} />
        </Button>
      </div>
      <Modal className={styles.modal} isOpen={state === "nav"}>
        <Dialog
          className={styles.dialog}
          aria-label={intl.formatMessage({
            id: "header.menu",
            defaultMessage: "Menu",
          })}
        >
          {children}
        </Dialog>
      </Modal>
    </div>
  )
}
