"use client"

import { useRef } from "react"

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

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

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)
    }
  }

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

  return null
}
