'use client'

import { useEffect, useRef, useState } from 'react'
import { useRecoilValue } from 'recoil'
import { useMessage } from '@/hooks/useMessage'
import { canvasState } from '@/store/canvasAtom'
import { useSwal } from '@/hooks/useSwal'
import { useObjectBatch } from '@/hooks/object/useObjectBatch'
import { POLYGON_TYPE } from '@/common/common'
import WithDraggable from '@/components/common/draggable/WithDraggable'
import OpenSpace from '@/components/floor-plan/modal/object/type/OpenSpace'
import Shadow from '@/components/floor-plan/modal/object/type/Shadow'
import TriangleDormer from '@/components/floor-plan/modal/object/type/TriangleDormer'
import PentagonDormer from '@/components/floor-plan/modal/object/type/PentagonDormer'
import { usePopup } from '@/hooks/usePopup'

export default function ObjectSetting({ id, pos = { x: 50, y: 230 } }) {
  const { getMessage } = useMessage()
  const canvas = useRecoilValue(canvasState)
  const [buttonAct, setButtonAct] = useState(1)
  const { swalFire } = useSwal()
  const [isHidden, setIsHidden] = useState(false)
  const { applyOpeningAndShadow, applyDormers } = useObjectBatch({ isHidden, setIsHidden })
  const { closePopup } = usePopup()

  const surfaceShapePolygons = canvas?.getObjects().filter((obj) => obj.name === POLYGON_TYPE.ROOF)
  //오브젝트 배치로 넘어오면 면형상 선택 불가
  useEffect(() => {
    canvas.discardActiveObject()
    surfaceShapePolygons.forEach((obj) => {
      obj.set({ selectable: false })
    })
  }, [])

  /**
   * 개구배치, 그림자배치
   */
  const objectPlacement = {
    typeRef: useRef([]), //프리입력, 치수입력
    widthRef: useRef(null),
    heightRef: useRef(null),
    isCrossRef: useRef(null),
  }

  const dormerPlacement = {
    widthRef: useRef(null),
    heightRef: useRef(null),
    pitchRef: useRef(null),
    offsetRef: useRef(null),
    offsetWidthRef: useRef(null),
    directionRef: useRef(null),
  }

  const applyObject = () => {
    if (surfaceShapePolygons.length === 0) {
      swalFire({ text: getMessage('batch.object.outside.roof'), icon: 'error' })
      return
    }

    //개구배치, 그림자배치
    if (buttonAct === 1 || buttonAct === 2) {
      applyOpeningAndShadow(objectPlacement, buttonAct)
    } else {
      const height = dormerPlacement.heightRef.current !== null ? dormerPlacement.heightRef.current.value / 10 : 0
      const width = dormerPlacement.widthRef.current !== null ? dormerPlacement.widthRef.current.value / 10 : 0 //triangle일때는 없음
      const pitch = dormerPlacement.pitchRef.current !== null ? Number(dormerPlacement.pitchRef.current.value) : 0
      const offsetRef =
        dormerPlacement.offsetRef.current !== null
          ? dormerPlacement.offsetRef.current.value === ''
            ? 0
            : parseInt(dormerPlacement.offsetRef.current.value) / 10
          : 0
      const offsetWidthRef =
        dormerPlacement.offsetWidthRef.current !== null
          ? dormerPlacement.offsetWidthRef.current.value === ''
            ? 0
            : parseInt(dormerPlacement.offsetWidthRef.current.value) / 10
          : 0
      const directionRef = dormerPlacement.directionRef.current

      const dormerParams = {
        height: height,
        width: width,
        pitch: pitch,
        offsetRef: offsetRef,
        offsetWidthRef: offsetWidthRef,
        directionRef: directionRef,
      }

      applyDormers(dormerParams, buttonAct)
    }
    setIsHidden(true)
  }

  const buttonMenu = [
    { id: 1, name: getMessage('modal.object.setting.type.open.space.placement') },
    { id: 2, name: getMessage('modal.object.setting.type.shadow.placement') },
    { id: 3, name: getMessage('modal.object.setting.type.triangle.dormer') },
    { id: 4, name: getMessage('modal.object.setting.type.pentagon.dormer') },
  ]

  return (
    <WithDraggable isShow={true} pos={pos} className="lrr" isHidden={isHidden}>
      <WithDraggable.Header title={getMessage('plan.menu.placement.surface.object')} onClose={() => closePopup(id)} />
      <WithDraggable.Body>
        <div className="modal-btn-wrap">
          {buttonMenu.map((item) => (
            <button key={item.id} className={`btn-frame modal ${buttonAct === item.id ? 'act' : ''}`} onClick={() => setButtonAct(item.id)}>
              {item.name}
            </button>
          ))}
        </div>
        <div className="properties-setting-wrap outer">
          {buttonAct === 1 && <OpenSpace ref={objectPlacement} />}
          {buttonAct === 2 && <Shadow ref={objectPlacement} />}
          {buttonAct === 3 && <TriangleDormer ref={dormerPlacement} />}
          {buttonAct === 4 && <PentagonDormer ref={dormerPlacement} />}
        </div>
        <div className="grid-btn-wrap">
          <button
            className="btn-frame modal act"
            onClick={() => {
              applyObject()
            }}
          >
            {getMessage('write')}
          </button>
        </div>
      </WithDraggable.Body>
    </WithDraggable>
  )
}
