'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 } from 'recoil'
import { correntObjectNoState } from '@/store/settingAtom'

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

  const { closeAll } = usePopup()
  const { menuNumber, setMenuNumber } = useCanvasMenu()
  const { fetchSettings, fetchBasicSettings } = useCanvasSetting()

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

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

    if(menuNumber === null) {
      setMenuNumber(1)
    }
    fetchSettings()
    fetchBasicSettings()

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

  const modalProps = {
    menuNumber,
    setMenuNumber,
  }

  return (
    <>
      <div className="canvas-wrap">
        <CanvasMenu {...modalProps} />
        <div className={`canvas-content ${menuNumber === 2 || menuNumber === 3 || menuNumber === 4 ? 'active' : ''}`}>{children}</div>
      </div>
    </>
  )
}
