"use client"

import { useRef } from "react"

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

import { ChevronDownSmallIcon, ChevronRightIcon } from "@/components/Icons"
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 type { NavigationMenuItemProps } from "@/types/components/header/navigationMenuItem"

export default function MenuItem({ item, isMobile }: NavigationMenuItemProps) {
  const { openMegaMenu, toggleMegaMenu } = 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)
  })

  return submenu.length ? (
    <>
      <MainMenuButton
        onClick={() => toggleMegaMenu(megaMenuTitle)}
        className={`${styles.navigationMenuItem} ${isMobile ? styles.mobile : styles.desktop}`}
      >
        {title}
        {isMobile ? (
          <ChevronRightIcon
            className={`${styles.chevron}`}
            color="red"
            height={20}
            width={20}
          />
        ) : (
          <ChevronDownSmallIcon
            className={`${styles.chevron} ${isMegaMenuOpen ? styles.isExpanded : ""}`}
            color="red"
          />
        )}
      </MainMenuButton>
      <div
        ref={megaMenuRef}
        className={`${styles.dropdown} ${isMegaMenuOpen ? styles.isExpanded : ""}`}
      >
        {isMegaMenuOpen ? (
          <MegaMenu
            isMobile={isMobile}
            title={title}
            seeAllLink={seeAllLink}
            submenu={submenu}
            card={card}
          />
        ) : null}
      </div>
    </>
  ) : (
    <Link
      className={`${styles.navigationMenuItem} ${isMobile ? styles.mobile : styles.desktop}`}
      variant="navigation"
      weight="bold"
      href={link!.url}
    >
      {title}
    </Link>
  )
}
