'use client'

import { useEffect } from 'react'

import { useMessage } from '@/hooks/useMessage'
import useMenu from '@/hooks/common/useMenu'
import { canvasState, currentMenuState } from '@/store/canvasAtom'
import { useRecoilState, useRecoilValue, useResetRecoilState } from 'recoil'
import { subMenusState } from '@/store/menuAtom'
import { useCanvasMenu } from '@/hooks/common/useCanvasMenu'
import { commonUtilsState } from '@/store/commonUtilsAtom'

export default function MenuDepth01() {
  const canvas = useRecoilValue(canvasState)
  const { getMessage } = useMessage()
  const { handleMenu } = useMenu()
  const { selectedMenu, setSelectedMenu } = useCanvasMenu()
  const [currentMenu, setCurrentMenu] = useRecoilState(currentMenuState)
  const subMenus = useRecoilValue(subMenusState)
  const resetCommonUtils = useResetRecoilState(commonUtilsState)

  const onClickMenu = ({ id, menu }) => {
    resetCommonUtils()
    if (menu === currentMenu) {
      handleMenu(selectedMenu)
    } else {
      setCurrentMenu(menu)
    }
  }

  useEffect(() => {
    handleMenu(selectedMenu)
    canvas?.discardActiveObject()
  }, [currentMenu])
  return (
    <div className="canvas-depth2-inner">
      <ul className="canvas-depth2-list">
        {subMenus[selectedMenu]?.map((menu) => {
          return (
            <li key={menu.id} className={`canvas-depth2-item ${menu.menu === currentMenu ? 'active' : ''}`}>
              <button onClick={() => onClickMenu(menu)}>{getMessage(menu.name)}</button>
            </li>
          )
        })}
      </ul>
    </div>
  )
}
