"use client"

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

import { ChevronDownIcon, ChevronRightIcon } from "@/components/Icons"
import Link from "@/components/TempDesignSystem/Link"
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 { submenu, title, link, seeAllLink, card } = item
  const isMegaMenuOpen = openMegaMenu === title

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

  return submenu.length ? (
    <>
      <MainMenuButton
        onClick={() => toggleMegaMenu(title)}
        className={`${styles.navigationMenuItem} ${isMobile ? styles.mobile : styles.desktop}`}
      >
        {title}
        {isMobile ? (
          <ChevronRightIcon className={`${styles.chevron}`} color="red" />
        ) : (
          <ChevronDownIcon
            className={`${styles.chevron} ${isMegaMenuOpen ? styles.isExpanded : ""}`}
            color="red"
          />
        )}
      </MainMenuButton>
      <div
        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}`}
      color="burgundy"
      href={link!.url}
    >
      {title}
    </Link>
  )
}
