'use client'

import { useContext, useEffect, useRef } from 'react'

import { useRecoilState, useRecoilValue, useResetRecoilState } from 'recoil'

import QContextMenu from '@/components/common/context-menu/QContextMenu'
import PanelBatchStatistics from '@/components/floor-plan/modal/panelBatch/PanelBatchStatistics'
import ImgLoad from '@/components/floor-plan/modal/ImgLoad'
import { useCanvas } from '@/hooks/useCanvas'
import { usePlan } from '@/hooks/usePlan'
import { useContextMenu } from '@/hooks/useContextMenu'
import { useCanvasConfigInitialize } from '@/hooks/common/useCanvasConfigInitialize'
import { currentMenuState } from '@/store/canvasAtom'
import { totalDisplaySelector } from '@/store/settingAtom'
import { MENU } from '@/common/common'
import { FloorPlanContext } from '@/app/floor-plan/FloorPlanProvider'
import { QcastContext } from '@/app/QcastProvider'
import {
  makersState,
  modelsState,
  moduleStatisticsState,
  pcsCheckState,
  selectedMakerState,
  selectedModelsState,
  seriesState,
} from '@/store/circuitTrestleAtom'
import { useCanvasPopupStatusController } from '@/hooks/common/useCanvasPopupStatusController'

export default function CanvasFrame() {
  const canvasRef = useRef(null)
  const { canvas } = useCanvas('canvas')
  const { canvasLoadInit, gridInit } = useCanvasConfigInitialize()
  const currentMenu = useRecoilValue(currentMenuState)
  const { floorPlanState } = useContext(FloorPlanContext)
  const { contextMenu, handleClick } = useContextMenu()
  const { plans, currentCanvasPlan } = usePlan()
  const totalDisplay = useRecoilValue(totalDisplaySelector) // 집계표 표시 여부
  const { setIsGlobalLoading } = useContext(QcastContext)
  const resetModuleStatisticsState = useResetRecoilState(moduleStatisticsState)
  const resetMakersState = useResetRecoilState(makersState)
  const resetSelectedMakerState = useResetRecoilState(selectedMakerState)
  const resetSeriesState = useResetRecoilState(seriesState)
  const resetModelsState = useResetRecoilState(modelsState)
  const resetSelectedModelsState = useResetRecoilState(selectedModelsState)
  const resetPcsCheckState = useResetRecoilState(pcsCheckState)
  const { handleModuleSelectionTotal } = useCanvasPopupStatusController()
  const loadCanvas = () => {
    if (canvas) {
      canvas?.clear() // 캔버스를 초기화합니다.
      if (currentCanvasPlan) {
        const plan = plans.find((plan) => plan.id === currentCanvasPlan.id)
        if (plan?.canvasStatus && floorPlanState.objectNo === currentCanvasPlan.objectNo) {
          canvas?.loadFromJSON(JSON.parse(plan.canvasStatus), function () {
            canvasLoadInit() //config된 상태로 캔버스 객체를 그린다
            canvas?.renderAll() // 캔버스를 다시 그립니다.
          })
        }
      }
      gridInit()
    }
  }

  useEffect(() => {
    loadCanvas()
    resetRecoilData()
    Object.keys(currentCanvasPlan).length > 0 && handleModuleSelectionTotal()
  }, [currentCanvasPlan, canvas])

  useEffect(() => {
    setIsGlobalLoading(false)
  }, [])

  const resetRecoilData = () => {
    resetModuleStatisticsState()
    resetMakersState()
    resetSelectedMakerState()
    resetSeriesState()
    resetModelsState()
    resetSelectedModelsState()
    resetPcsCheckState()
  }

  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) => 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) &&
        totalDisplay && <PanelBatchStatistics />}
      {/* 이미지 로드 팝업 */}
      <ImgLoad />
    </div>
  )
}
