'use client'

import { useEffect, useState } from 'react'
import CanvasFrame from './CanvasFrame'
import { useRecoilState, useRecoilValue } from 'recoil'
import { currentMenuState, stepState } from '@/store/canvasAtom'

export default function CanvasLayout() {
  const [plans, setPlans] = useState([
    { id: 0, name: 'Plan 1', isCurrent: false },
    { id: 1, name: 'Plan 2', isCurrent: false },
    { id: 2, name: 'Plan 3', isCurrent: false },
  ])
  const [idxNum, setIdxNum] = useState(null)

  const onClickPlane = (num) => {
    setIdxNum(num)
  }

  const handleDeletePlan = (e, id) => {
    e.stopPropagation() // 이벤트 버블링 방지
    setPlans(plans.filter((plan) => plan.id !== id)) // 삭제할 아이디와 다른 아이템만 남김
  }

  const addNewPlan = () => {
    setPlans([...plans, { id: plans.length, name: `Plan ${plans.length + 1}` }])
  }

  useEffect(() => {
    if (plans.length === 1) {
      setPlans([{ id: 0, name: 'Plan 1', isCurrent: false }])
    }
  }, [])

  return (
    <div className="canvas-layout">
      <div className="canvas-page-list">
        <div className="canvas-plane-wrap">
          {plans.map((plan, idx) => (
            <button key={plan.id} className={`canvas-page-box ${idx === idxNum ? 'on' : ''}`} onClick={() => onClickPlane(idx)}>
              <span>{plan.name}</span>
              <i className="close" onClick={(e) => handleDeletePlan(e, plan.id)}></i>
            </button>
          ))}
        </div>
        <button className="plane-add" onClick={addNewPlan}>
          <span></span>
        </button>
      </div>
      <CanvasFrame />
    </div>
  )
}
