'use client'

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

export default function CanvasLayout() {
  const { session } = useContext(SessionContext)
  const [objectNo, setObjectNo] = useState('test123240822001') // 이후 삭제 필요
  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">
        <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}</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>
      <CanvasFrame plan={plans.find((plan) => plan.isCurrent === true)} />
    </div>
  )
}
