'use client'

import { useContext, useEffect, useState } from 'react'
import { useRecoilState, useRecoilValue } from 'recoil'
import CanvasFrame from './CanvasFrame'
import { useMessage } from '@/hooks/useMessage'
import { useSwal } from '@/hooks/useSwal'
import { usePlan } from '@/hooks/usePlan'
import { modifiedPlansState } from '@/store/canvasAtom'
import { globalLocaleStore } from '@/store/localeAtom'
import { SessionContext } from '@/app/SessionProvider'
import { useCanvasMenu } from '@/hooks/common/useCanvasMenu'

export default function CanvasLayout({ children }) {
  // const { menuNumber } = props
  const { menuNumber } = useCanvasMenu()
  const { session } = useContext(SessionContext)
  const [objectNo, setObjectNo] = useState('test123240822001') // 이후 삭제 필요
  const [modifiedPlans, setModifiedPlans] = useRecoilState(modifiedPlansState) // 변경된 canvas plan
  const globalLocaleState = useRecoilValue(globalLocaleStore)

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

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

  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) => (
            <button
              key={`plan-${plan.id}`}
              className={`canvas-page-box ${plan.isCurrent === true ? 'on' : ''}`}
              onClick={() => handleCurrentPlan(session.userId, plan.id)}
            >
              <span>
                {plan.name}
                {modifiedPlans.some((modifiedPlan) => modifiedPlan === plan.id) && ' [ M ]'}
              </span>
              <i
                className="close"
                onClick={(e) =>
                  swalFire({
                    text: `${plan.name} ` + getMessage('plan.message.confirm.delete'),
                    type: 'confirm',
                    confirmFn: () => {
                      handleDeletePlan(e, plan.id)
                    },
                  })
                }
              ></i>
            </button>
          ))}
        </div>
        {plans.length < 10 && (
          <button className="plane-add" onClick={() => handleAddPlan(session.userId, objectNo)}>
            <span></span>
          </button>
        )}
      </div>
      {children}
    </div>
  )
}
