'use client'

import { 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 { globalLocaleStore } from '@/store/localeAtom'
import { currentCanvasPlanState, initCanvasPlansState, plansState } from '@/store/canvasAtom'
import { sessionStore } from '@/store/commonAtom'

export default function CanvasLayout() {
  const [objectNo, setObjectNo] = useState('test123240822001') // 이후 삭제 필요
  const [planNum, setPlanNum] = useState(0)
  const [currentCanvasPlan, setCurrentCanvasPlan] = useRecoilState(currentCanvasPlanState)
  const [initCanvasPlans, setInitCanvasPlans] = useRecoilState(initCanvasPlansState)
  const [plans, setPlans] = useRecoilState(plansState)
  const globalLocaleState = useRecoilValue(globalLocaleStore)
  const sessionState = useRecoilValue(sessionStore)

  const { getMessage } = useMessage()
  const { swalFire } = useSwal()
  const { getCanvasByObjectNo, delCanvasById, checkModifiedCanvasPlan, saveCanvas } = usePlan()

  const handleCurrentPlan = (newCurrentId) => {
    // console.log('currentPlan newCurrentId: ', newCurrentId)
    if (!currentCanvasPlan || currentCanvasPlan.id !== newCurrentId) {
      if (currentCanvasPlan?.id && checkModifiedCanvasPlan()) {
        swalFire({
          html: getMessage('common.message.confirm.save') + `</br>${currentCanvasPlan.name}`,
          type: 'confirm',
          confirmFn: async () => {
            await saveCanvas(sessionState.userId)
            updateCurrentPlan(newCurrentId)
          },
          denyFn: () => {
            updateCurrentPlan(newCurrentId)
          },
        })
      } else {
        updateCurrentPlan(newCurrentId)
      }
    }
  }
  const updateCurrentPlan = (newCurrentId) => {
    setPlans((plans) =>
      plans.map((plan) => {
        return { ...plan, isCurrent: plan.id === newCurrentId }
      }),
    )
  }
  useEffect(() => {
    setCurrentCanvasPlan(plans.find((plan) => plan.isCurrent) || null)
  }, [plans])

  const handleDeletePlan = (e, id) => {
    e.stopPropagation() // 이벤트 버블링 방지

    if (initCanvasPlans.some((plan) => plan.id === id)) {
      delCanvasById(id)
        .then((res) => {
          swalFire({ text: getMessage('common.message.delete') })
          // console.log('[DELETE] canvas-statuses res :::::::: %o', res)
          setInitCanvasPlans((initCanvasPlans) => initCanvasPlans.filter((plan) => plan.id !== id))
          setPlans((plans) => plans.filter((plan) => plan.id !== id))
        })
        .catch((error) => {
          swalFire({ text: error.message, icon: 'error' })
          // console.error('[DELETE] canvas-statuses res error :::::::: %o', error)
        })
    } else {
      setPlans((plans) => plans.filter((plan) => plan.id !== id))
      swalFire({ text: getMessage('common.message.delete') })
    }

    // 삭제 후 last 데이터에 포커싱
    const lastPlan = plans.filter((plan) => plan.id !== id).at(-1)
    if (!lastPlan) {
      setPlanNum(0)
      setCurrentCanvasPlan(null)
    } else if (id !== lastPlan.id) {
      handleCurrentPlan(lastPlan.id)
    }
  }

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

  useEffect(() => {
    if (!currentCanvasPlan) {
      getCanvasByObjectNo(sessionState.userId, objectNo).then((res) => {
        // console.log('canvas 목록 ', res)
        if (res.length > 0) {
          setInitCanvasPlans(res)
          setPlans(res)
          handleCurrentPlan(res.at(-1).id) // last 데이터에 포커싱
          setPlanNum(res.length)
        } else {
          addNewPlan()
        }
      })
    }
  }, [])

  return (
    <div className="canvas-layout">
      <div className="canvas-page-list">
        <div className="canvas-plane-wrap">
          {plans.map((plan) => (
            <button key={plan.id} className={`canvas-page-box ${plan.isCurrent === true ? 'on' : ''}`} onClick={() => handleCurrentPlan(plan.id)}>
              <span>{plan.name}</span>
              <i
                className="close"
                onClick={(e) =>
                  swalFire({
                    html: getMessage('common.message.confirm.delete') + `</br>${plan.name}`,
                    type: 'confirm',
                    confirmFn: () => {
                      handleDeletePlan(e, plan.id)
                    },
                  })
                }
              ></i>
            </button>
          ))}
        </div>
        <button className="plane-add" onClick={addNewPlan}>
          <span></span>
        </button>
      </div>
      <CanvasFrame plan={plans.find((plan) => plan.isCurrent === true)} />
    </div>
  )
}
