'use client'

import { useEffect, useRef } from 'react'

import { useRecoilState, useRecoilValue } from 'recoil'

import { useCanvas } from '@/hooks/useCanvas'
import { useEvent } from '@/hooks/useEvent'
import { usePlan } from '@/hooks/usePlan'
import { useContextMenu } from '@/hooks/useContextMenu'
import { currentMenuState, currentObjectState, modifiedPlanFlagState } from '@/store/canvasAtom'
import { useCanvasEvent } from '@/hooks/useCanvasEvent'
import QContextMenu from '@/components/common/context-menu/QContextMenu'
import { useCanvasConfigInitialize } from '@/hooks/common/useCanvasConfigInitialize'
import { MENU } from '@/common/common'
import PanelBatchStatistics from '@/components/floor-plan/modal/panelBatch/PanelBatchStatistics'

export default function CanvasFrame({ plan }) {
  const canvasRef = useRef(null)
  const [modifiedPlanFlag, setModifiedPlanFlag] = useRecoilState(modifiedPlanFlagState)
  const { canvas } = useCanvas('canvas')
  const { handleZoomClear } = useCanvasEvent()
  const { canvasLoadInit, gridInit } = useCanvasConfigInitialize()
  const currentObject = useRecoilValue(currentObjectState)
  const currentMenu = useRecoilValue(currentMenuState)
  const { contextMenu, handleClick, handleKeyup } = useContextMenu()
  const { checkCanvasObjectEvent, checkUnsavedCanvasPlan, resetModifiedPlans } = usePlan()
  useEvent()

  const loadCanvas = () => {
    if (canvas) {
      canvas?.clear() // 캔버스를 초기화합니다.
      if (plan?.canvasStatus) {
        canvas?.loadFromJSON(JSON.parse(plan.canvasStatus), function () {
          canvasLoadInit() //config된 상태로 캔버스 객체를 그린다
          canvas?.renderAll() // 캔버스를 다시 그립니다.
        })
      }
      gridInit()
    }
  }

  useEffect(() => {
    if (modifiedPlanFlag && plan?.id) {
      checkCanvasObjectEvent(plan.id)
    }
  }, [modifiedPlanFlag])

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

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

      <QContextMenu contextRef={canvasRef} canvasProps={canvas} handleKeyup={handleKeyup}>
        {contextMenu.map((menus, index) => (
          <ul key={index}>
            {menus.map((menu) => (
              <li key={menu.id} onClick={(e) => handleClick(e, menu)}>
                {menu.name}
              </li>
            ))}
          </ul>
        ))}
      </QContextMenu>
      {[
        MENU.MODULE_CIRCUIT_SETTING.BASIC_SETTING,
        MENU.MODULE_CIRCUIT_SETTING.CIRCUIT_TRESTLE_SETTING,
        MENU.MODULE_CIRCUIT_SETTING.PLAN_ORIENTATION,
      ].includes(currentMenu) && <PanelBatchStatistics />}
    </div>
  )
}
