import WithDraggable from '@/components/common/draggable/WithDraggable'
import { useRecoilValue } from 'recoil'
import { contextPopupPositionState } from '@/store/popupAtom'
import { usePopup } from '@/hooks/usePopup'
import { useMessage } from '@/hooks/useMessage'
import { useEffect, useState } from 'react'
import { canvasState } from '@/store/canvasAtom'
import { POLYGON_TYPE } from '@/common/common'
import { useModule } from '@/hooks/module/useModule'
import { useSwal } from '@/hooks/useSwal'
export const PANEL_EDIT_TYPE = {
  MOVE: 'move',
  MOVE_ALL: 'moveAll',
  COPY: 'copy',
  COPY_ALL: 'copyAll',
  COLUMN_MOVE: 'columnMove',
  COLUMN_COPY: 'columnCopy',
  ROW_MOVE: 'rowMove',
  ROW_COPY: 'rowCopy',
}

export default function PanelEdit(props) {
  const contextPopupPosition = useRecoilValue(contextPopupPositionState)
  const { id, pos = contextPopupPosition, type = PANEL_EDIT_TYPE.MOVE, apply } = props
  const { closePopup } = usePopup()
  const [length, setLength] = useState(0)
  const [direction, setDirection] = useState('up')
  const { getMessage } = useMessage()
  const canvas = useRecoilValue(canvasState)
  const { swalFire } = useSwal()
  const { moduleMove, moduleCopy, moduleMultiMove, moduleMultiCopy, moduleMoveAll, moduleCopyAll } = useModule()
  useEffect(() => {
    if (!canvas) {
      const isSetupModules = canvas.getObjects().filter((obj) => obj.name === 'module') // selectedObj에 없는 객체만 필터링
      isSetupModules.forEach((obj) => obj.set({ lockMovementX: false, lockMovementY: false }))
    }

    //팝업 닫을때 선택 해제
    return () => {
      const modules = canvas.getObjects().filter((obj) => obj.name === 'module')
      modules.forEach((obj) => {
        obj.set({
          stroke: 'black',
          strokeWidth: 0.3,
        })
      })
      canvas?.discardActiveObject() //선택해제
      canvas.renderAll()
    }
  }, [])

  //모듈 이동 적용
  const handleApply = () => {
    if (length <= 0) {
      swalFire({
        title: getMessage('common.message.please.input.over', [1]),
        type: 'alert',
        icon: 'error',
      })
      return
    }
    const completeSurfaces = canvas.getObjects().filter((obj) => obj.name === POLYGON_TYPE.MODULE_SETUP_SURFACE && obj.isComplete)

    if (completeSurfaces.length > 0) {
      swalFire({
        title: getMessage('modal.module.can.not.edit'),
        type: 'alert',
        icon: 'error',
      })
      return
    }

    switch (type) {
      case PANEL_EDIT_TYPE.MOVE:
        moduleMove(length, direction)
        break
      case PANEL_EDIT_TYPE.MOVE_ALL:
        moduleMoveAll(length, direction, props.arrayData)
        break
      case PANEL_EDIT_TYPE.COPY:
        moduleCopy(length, direction)
        break
      case PANEL_EDIT_TYPE.COPY_ALL:
        moduleCopyAll(length, direction, props.arrayData)
        break
      case PANEL_EDIT_TYPE.COLUMN_MOVE:
        moduleMultiMove('column', length, direction)
        break
      case PANEL_EDIT_TYPE.COLUMN_COPY:
        moduleMultiCopy('column', length, direction)
        break
      case PANEL_EDIT_TYPE.ROW_MOVE:
        moduleMultiMove('row', length, direction)
        break
      case PANEL_EDIT_TYPE.ROW_COPY:
        moduleMultiCopy('row', length, direction)
        break
    }
    // closePopup(id)
  }

  return (
    <WithDraggable isShow={true} pos={pos} className="xm">
      <WithDraggable.Header
        title={getMessage(
          [PANEL_EDIT_TYPE.MOVE, PANEL_EDIT_TYPE.MOVE_ALL, PANEL_EDIT_TYPE.COLUMN_MOVE, PANEL_EDIT_TYPE.ROW_MOVE].includes(type)
            ? 'modal.move.setting'
            : 'modal.copy.setting',
        )}
        onClose={() => closePopup(id)}
      />
      <WithDraggable.Body>
        <div className="grid-option-tit">
          {getMessage(
            [PANEL_EDIT_TYPE.MOVE, PANEL_EDIT_TYPE.MOVE_ALL, PANEL_EDIT_TYPE.COLUMN_MOVE, PANEL_EDIT_TYPE.ROW_MOVE].includes(type)
              ? 'modal.move.setting.info'
              : 'modal.copy.setting.info',
          )}
        </div>
        <div className="grid-option-wrap">
          <div className="grid-option-box">
            <div className="grid-input-form">
              <span className="mr10">{getMessage('margin')}</span>
              <div className="input-grid mr5">
                <input type="text" className="input-origin" defaultValue={0} onKeyUp={(e) => setLength(e.target.value)} />
              </div>
              <span>mm</span>
            </div>
            <div className="grid-direction">
              <button
                className={`direction up ${direction === 'up' ? 'act' : ''}`}
                onClick={() => {
                  setDirection('up')
                }}
              ></button>
              <button
                className={`direction down ${direction === 'down' ? 'act' : ''}`}
                onClick={() => {
                  setDirection('down')
                }}
              ></button>
              <button
                className={`direction left ${direction === 'left' ? 'act' : ''}`}
                onClick={() => {
                  setDirection('left')
                }}
              ></button>
              <button
                className={`direction right ${direction === 'right' ? 'act' : ''}`}
                onClick={() => {
                  setDirection('right')
                }}
              ></button>
            </div>
          </div>
        </div>
        <div className="grid-btn-wrap">
          <button className="btn-frame modal mr5" onClick={handleApply}>
            {getMessage(
              [PANEL_EDIT_TYPE.MOVE, PANEL_EDIT_TYPE.MOVE_ALL, PANEL_EDIT_TYPE.COLUMN_MOVE, PANEL_EDIT_TYPE.ROW_MOVE].includes(type)
                ? 'modal.move.save'
                : 'modal.copy.save',
            )}
          </button>
        </div>
      </WithDraggable.Body>
    </WithDraggable>
  )
}
