import WithDraggable from '@/components/common/draggable/WithDraggable'
import { useMessage } from '@/hooks/useMessage'
import { usePopup } from '@/hooks/usePopup'
import { useRecoilState, useRecoilValue } from 'recoil'
import { contextPopupPositionState } from '@/store/popupAtom'
import { useCanvas } from '@/hooks/useCanvas'
import { canvasState, currentObjectState } from '@/store/canvasAtom'
import { useEffect, useState } from 'react'
import { useSwal } from '@/hooks/useSwal'
import { set } from 'react-hook-form'

export default function GridMove(props) {
  const contextPopupPosition = useRecoilValue(contextPopupPositionState)
  const { id, pos = contextPopupPosition } = props
  const canvas = useRecoilValue(canvasState)
  const { getMessage } = useMessage()
  const { closePopup } = usePopup()
  const { swalFire } = useSwal()
  const [currentObject, setCurrentObject] = useRecoilState(currentObjectState)
  const [isAll, setIsAll] = useState(false)
  const [verticalSize, setVerticalSize] = useState('0')
  const [horizonSize, setHorizonSize] = useState('0')
  const [arrow1, setArrow1] = useState(null)
  const [arrow2, setArrow2] = useState(null)

  useEffect(() => {
    if (currentObject?.direction === 'vertical') {
      setArrow1(null)
      setVerticalSize('0')
    } else {
      setArrow2(null)
      setHorizonSize('0')
    }
  }, [currentObject])

  const handleApply = () => {
    if (currentObject?.direction === 'vertical') {
      if (!horizonSize || !arrow2) {
        swalFire({ title: getMessage('length.direction.is.required'), type: 'alert' })
        return
      }
    } else {
      if (!verticalSize || !arrow1) {
        swalFire({ title: getMessage('length.direction.is.required'), type: 'alert' })
      }
    }

    if (isAll) {
      canvas
        .getObjects()
        .filter((obj) => ['lineGrid', 'tempGrid', 'dotGrid'].includes(obj.name))
        .forEach((grid) => {
          move(
            grid,
            arrow2 === '←' ? (Number(horizonSize) * -1) / 10 : Number(horizonSize) / 10,
            arrow1 === '↑' ? (Number(verticalSize) * -1) / 10 : Number(verticalSize) / 10,
          )
        })
    } else {
      move(
        currentObject,
        arrow2 === '←' ? (Number(horizonSize) * -1) / 10 : Number(horizonSize) / 10,
        arrow1 === '↑' ? (Number(verticalSize) * -1) / 10 : Number(verticalSize) / 10,
      )
    }
    canvas.renderAll()
    handleClose()
  }

  const move = (object, x, y) => {
    object.set({
      ...object,
      x1: object.direction === 'vertical' ? object.x1 + x : 0,
      x2: object.direction === 'vertical' ? object.x1 + x : canvas.width,
      y1: object.direction === 'vertical' ? 0 : object.y1 + y,
      y2: object.direction === 'vertical' ? canvas.height : object.y1 + y,
    })
  }

  const handleClose = () => {
    closePopup(id)
  }
  return (
    <WithDraggable isShow={true} pos={pos} className="xm">
      <WithDraggable.Header title={getMessage('modal.grid.move')} onClose={() => handleClose()} />
      <WithDraggable.Body>
        <div className="grid-option-tit">{getMessage('modal.grid.move.info')}</div>
        <div className="grid-option-wrap">
          <div className="d-check-box pop mb10">
            <input type="checkbox" id="ch99" checked={isAll} onChange={() => setIsAll(!isAll)} />
            <label htmlFor="ch99">{getMessage('modal.grid.move.all')}</label>
          </div>
          <div className="grid-option-box">
            <div className="move-form">
              <p className="mb5">{getMessage('modal.grid.move.length')}</p>
              <div className="input-move-wrap mb5">
                <div className="input-move">
                  <input
                    type="text"
                    className="input-origin"
                    value={verticalSize}
                    onChange={(e) => setVerticalSize(e.target.value)}
                    readOnly={!isAll && currentObject?.direction === 'vertical'}
                  />
                </div>
                <span>mm</span>
                <div className="direction-move-wrap">
                  <button
                    className={`direction up ${arrow1 === '↑' ? 'act' : ''} ${!isAll && currentObject?.direction === 'vertical' ? 'no-click' : ''}`}
                    onClick={() => {
                      setArrow1('↑')
                      document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowUp' }))
                    }}
                  ></button>
                  <button
                    className={`direction down ${arrow1 === '↓' ? 'act' : ''} ${!isAll && currentObject?.direction === 'vertical' ? 'no-click' : ''}`}
                    onClick={() => {
                      setArrow1('↓')
                      document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown' }))
                    }}
                  ></button>
                </div>
              </div>
              <div className="input-move-wrap">
                <div className="input-move">
                  <input
                    type="text"
                    className="input-origin"
                    value={horizonSize}
                    onChange={(e) => setHorizonSize(e.target.value)}
                    readOnly={!isAll && currentObject?.direction === 'horizontal'}
                  />
                </div>
                <span>mm</span>
                <div className="direction-move-wrap">
                  <button
                    className={`direction left ${arrow2 === '←' ? 'act' : ''} ${!isAll && currentObject?.direction === 'horizontal' ? 'no-click' : ''}`}
                    onClick={() => {
                      setArrow2('←')
                      document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowLeft' }))
                    }}
                  ></button>
                  <button
                    className={`direction right ${arrow2 === '→' ? 'act' : ''} ${!isAll && currentObject?.direction === 'horizontal' ? 'no-click' : ''}`}
                    onClick={() => {
                      setArrow2('→')
                      document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight' }))
                    }}
                  ></button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className="grid-btn-wrap">
          <button className="btn-frame modal act" onClick={handleApply}>
            {getMessage('modal.grid.move.save')}
          </button>
        </div>
      </WithDraggable.Body>
    </WithDraggable>
  )
}
