'use client'

import { useEffect, useRef } from 'react'

import { useCanvas } from '@/hooks/useCanvas'
import { useEvent } from '@/hooks/useEvent'
import QContextMenu from '@/components/common/context-menu/QContextMenu'
import { useContextMenu } from '@/hooks/useContextMenu'
import { useRecoilValue } from 'recoil'
import { currentObjectState } from '@/store/canvasAtom'

export default function CanvasFrame({ plan }) {
  const canvasRef = useRef(null)
  const { canvas } = useCanvas('canvas')
  const { contextMenu, currentContextMenu, setCurrentContextMenu } = useContextMenu()

  useEvent()

  const loadCanvas = () => {
    if (canvas) {
      canvas?.clear() // 캔버스를 초기화합니다.
      if (plan?.canvasStatus) {
        canvas?.loadFromJSON(JSON.parse(plan.canvasStatus), function () {
          canvas?.renderAll() // 캔버스를 다시 그립니다.
        })
      }
    }
  }

  useEffect(() => {
    loadCanvas()
  }, [plan, canvas])

  const onClickContextMenu = (index) => {}

  return (
    <div className="canvas-frame flex justify-center">
      <canvas ref={canvasRef} id={'canvas'}></canvas>
      <QContextMenu contextRef={canvasRef} canvasProps={canvas}>
        {contextMenu.map((menus, index) => (
          <ul key={index}>
            {menus.map((menu) => (
              <li onClick={(e) => setCurrentContextMenu(menu)}>{menu.name}</li>
            ))}
          </ul>
        ))}
      </QContextMenu>
      {currentContextMenu?.component}
    </div>
  )
}
