'use client'

import { useContext, useEffect } from 'react'
import { usePathname } from 'next/navigation'
import { useRecoilValue } from 'recoil'
import { FloorPlanContext } from '@/app/floor-plan/FloorPlanProvider'
import { SessionContext } from '@/app/SessionProvider'
import { useMessage } from '@/hooks/useMessage'
import { useSwal } from '@/hooks/useSwal'
import { usePlan } from '@/hooks/usePlan'
import { useCanvasMenu } from '@/hooks/common/useCanvasMenu'
import { globalLocaleStore } from '@/store/localeAtom'

export default function CanvasLayout({ children }) {
  // const { menuNumber } = props
  const pathname = usePathname()
  const { menuNumber } = useCanvasMenu()
  const { session } = useContext(SessionContext)
  const { floorPlanState } = useContext(FloorPlanContext)
  const { objectNo, pid } = floorPlanState
  const globalLocaleState = useRecoilValue(globalLocaleStore)

  const { getMessage } = useMessage()
  const { swalFire } = useSwal()
  const { plans, loadCanvasPlanData, handleCurrentPlan, handleAddPlan, handleDeletePlan } = usePlan()

  useEffect(() => {
    loadCanvasPlanData(session.userId, objectNo, pid)
  }, [])

  return (
    <div className="canvas-layout">
      <div className={`canvas-page-list ${menuNumber === 2 || menuNumber === 3 || menuNumber === 4 ? 'active' : ''}`}>
        <div className="canvas-plane-wrap">
          {plans.map((plan, index) => (
            <button
              key={`plan-${plan.id}`}
              className={`canvas-page-box ${plan.isCurrent === true ? 'on' : ''}`}
              onClick={() => handleCurrentPlan(plan.id)}
            >
              <span>{`Plan ${plan.planNo}`}</span>
              {index !== 0 && (
                <i
                  className="close"
                  onClick={(e) => {
                    //삭제 아이콘 눌렀는데 handleCurrentPlan실행되서 추가
                    e.stopPropagation()
                    swalFire({
                      text: `Plan ${plan.planNo} ` + getMessage('plan.message.confirm.delete'),
                      type: 'confirm',
                      confirmFn: () => {
                        handleDeletePlan(e, plan)
                      },
                    })
                  }}
                ></i>
              )}
            </button>
          ))}
        </div>
        {plans.length < 10 && !pathname.includes('/estimate') && !pathname.includes('/simulator') && (
          <button
            className="plane-add"
            onClick={async () => {
              await handleAddPlan(session.userId, objectNo)
            }}
          >
            <span></span>
          </button>
        )}
      </div>
      {children}
    </div>
  )
}
