'use client'

import { useEffect, useRef } from 'react'

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

export default function CanvasFrame({ plan }) {
  const canvasRef = useRef(null)
  const { canvas } = useCanvas('canvas')
  const { handleZoomClear } = useCanvasEvent()
  const { contextMenu, currentContextMenu, setCurrentContextMenu } = useContextMenu({
    externalFn: {
      handleZoomClear,
    },
  })
  const { checkCanvasObjectEvent, checkUnsavedCanvasPlan } = usePlan()

  const currentObject = useRecoilValue(currentObjectState)

  useEvent()

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

  useEffect(() => {
    // const checkEventName = [
    //   'object:modified',
    //   'object:moving',
    //   'object:scaling',
    //   'object:rotating',
    //   'object:skewing',
    //   'object:resizing',
    //   'object:selected',
    //   'object:added',
    //   'object:removed',
    // ]
    
    canvas?.off('object:added')
    canvas?.off('object:modified')
    canvas?.off('object:removed')

    loadCanvas()

    if (plan) {
      canvas?.on('object:added', (e) => {
        if (e?.target.name !== 'mouseLine') {
          checkCanvasObjectEvent(e, plan.id)
        }
      })
      canvas?.on('object:modified', (e) => {
        if (e?.target.name !== 'mouseLine') {
          checkCanvasObjectEvent(e, plan.id)
        }
      })
      canvas?.on('object:removed', (e) => {
        if (e?.target.name !== 'mouseLine') {
          checkCanvasObjectEvent(e, plan.id)
        }
      })
    }
  }, [plan, canvas])

  const onClickContextMenu = (index) => {}

  return (
    <div className="canvas-frame">
      <canvas ref={canvasRef} id="canvas" style={{ position: 'relative' }}></canvas>

      <QContextMenu contextRef={canvasRef} canvasProps={canvas}>
        {contextMenu.map((menus, index) => (
          <ul key={index}>
            {menus.map((menu) => (
              <li
                key={menu.id}
                onClick={(e) => {
                  if (menu.fn) {
                    menu.fn()
                  }
                  setCurrentContextMenu(menu)
                }}
              >
                {menu.name}
              </li>
            ))}
          </ul>
        ))}
      </QContextMenu>
      {currentContextMenu?.component}
    </div>
  )
}
