'use client'

import { useEffect } from 'react'
import CanvasMenu from '@/components/floor-plan/CanvasMenu'
import { useCanvasMenu } from '@/hooks/common/useCanvasMenu'
import { useCanvasSetting } from '@/hooks/option/useCanvasSetting'
import { usePopup } from '@/hooks/usePopup'
import '@/styles/contents.scss'
import { notFound, useSearchParams } from 'next/navigation'
import { useRecoilState, useResetRecoilState } from 'recoil'
import { correntObjectNoState } from '@/store/settingAtom'
import { currentMenuState } from '@/store/canvasAtom'

export default function FloorPlan({ children }) {
  const [correntObjectNo, setCurrentObjectNo] = useRecoilState(correntObjectNoState)
  const searchParams = useSearchParams()
  const objectNo = searchParams.get('objectNo')

  const { closeAll } = usePopup()
  const { selectedMenu, setSelectedMenu } = useCanvasMenu()
  const { fetchSettings } = useCanvasSetting()
  const resetCurrentMenu = useResetRecoilState(currentMenuState)
  useEffect(() => {
    return () => {
      resetCurrentMenu()
    }
  }, [])

  /**
   * URL 파라미터에서 objectNo 설정
   */
  useEffect(() => {
    if (!objectNo) {
      notFound()
    }
    setCurrentObjectNo(objectNo)
  }, [objectNo, setCurrentObjectNo])

  /**
   * 설정 데이터 fetch
   */
  useEffect(() => {
    /** correntObjectNo가 없으면 실행하지 않음 */
    if (!correntObjectNo) return

    /** CanvasSetting 데이터 fetch */
    fetchSettings()

    return () => {
      closeAll()
    }
  }, [correntObjectNo])

  const modalProps = {
    selectedMenu,
    setSelectedMenu,
  }

  return (
    <>
      <div className="canvas-wrap">
        <CanvasMenu {...modalProps} />
        <div className={`canvas-content ${selectedMenu === 'outline' || selectedMenu === 'surface' || selectedMenu === 'module' ? 'active' : ''}`}>
          {children}
        </div>
      </div>
    </>
  )
}
