"use client"

import { useRef } from "react"

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

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

import Link from "@/components/TempDesignSystem/Link"
import useClickOutside from "@/hooks/useClickOutside"
import { useHandleKeyUp } from "@/hooks/useHandleKeyUp"

import MainMenuButton from "../../MainMenuButton"
import MegaMenu from "../MegaMenu"

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

import { DropdownTypeEnum } from "@/types/components/dropdown/dropdown"
import type { NavigationMenuItemProps } from "@/types/components/header/navigationMenuItem"

export default function MenuItem({ item, isMobile }: NavigationMenuItemProps) {
  const { openMegaMenu, toggleMegaMenu, toggleDropdown, isHamburgerMenuOpen } =
    useDropdownStore()
  const megaMenuRef = useRef<HTMLDivElement>(null)
  const { submenu, title, link, seeAllLink, card } = item
  const megaMenuTitle = `${title}-${isMobile ? "mobile" : "desktop"}`
  const isMegaMenuOpen = openMegaMenu === megaMenuTitle

  useHandleKeyUp((event: KeyboardEvent) => {
    if (event.key === "Escape" && isMegaMenuOpen) {
      toggleMegaMenu(false)
    }
  })

  useClickOutside(megaMenuRef, isMegaMenuOpen && !isMobile, () => {
    toggleMegaMenu(false)
  })

  function handleNavigate() {
    if (isHamburgerMenuOpen) {
      toggleDropdown(DropdownTypeEnum.HamburgerMenu)
    }
  }

  return submenu.length ? (
    <>
      <MainMenuButton
        onClick={() => toggleMegaMenu(megaMenuTitle)}
        className={`${styles.navigationMenuItem} ${isMobile ? styles.mobile : ""}`}
      >
        {title}
        {isMobile ? (
          <MaterialIcon
            icon="chevron_right"
            size={20}
            className={`${styles.chevron}`}
            color="Icon/Interactive/Accent"
          />
        ) : (
          <MaterialIcon
            icon="keyboard_arrow_down"
            size={20}
            className={`${styles.chevron} ${isMegaMenuOpen ? styles.isExpanded : ""}`}
            color="Icon/Interactive/Accent"
          />
        )}
      </MainMenuButton>
      <div
        ref={megaMenuRef}
        className={`${styles.dropdown} ${isMegaMenuOpen ? styles.isExpanded : ""}`}
      >
        <MegaMenu
          isMobile={isMobile}
          title={title}
          seeAllLink={seeAllLink}
          submenu={submenu}
          card={card}
          isOpen={isMegaMenuOpen}
        />
      </div>
    </>
  ) : (
    <Link
      className={`${styles.navigationMenuItem} ${isMobile ? styles.mobile : ""}`}
      variant="navigation"
      weight="bold"
      onClick={handleNavigate}
      href={link!.url}
    >
      {title}
    </Link>
  )
}
