import { useEffect, useRef, useState } from 'react'
import WithDraggable from '@/components/common/draggable/WithDraggable'
import { usePopup } from '@/hooks/usePopup'
import { useMessage } from '@/hooks/useMessage'
import { useRecoilState, useRecoilValue } from 'recoil'
import { contextPopupPositionState } from '@/store/popupAtom'
import QSelectBox from '@/components/common/select/QSelectBox'
import { canvasState, pitchTextSelector } from '@/store/canvasAtom'
import { defaultSlope } from '@/store/commonAtom'
import { re } from 'mathjs'
import { basicSettingState } from '@/store/settingAtom'
import { getChonByDegree } from '@/util/canvas-util'

export default function DimensionLineSetting(props) {
  const contextPopupPosition = useRecoilValue(contextPopupPositionState)
  let { id, setIsShow, pos = contextPopupPosition } = props
  const { getMessage } = useMessage()
  const { closePopup } = usePopup()
  const canvas = useRecoilValue(canvasState)
  const pitchText = useRecoilState(pitchTextSelector)
  const SelectOption01 = defaultSlope
  const [basicLength, setBasicLength] = useState(0)
  const [slopeAble, setSlopeAble] = useState(false)
  const basicSetting = useRecoilValue(basicSettingState)
  const changeSlopeRef = useRef()
  const [options, setOptions] = useState([])
  const [changeLength, setChangeLength] = useState(null)
  const [selectedSlope1, setSelectedSlope1] = useState(null)
  const [selectedSlope2, setSelectedSlope2] = useState(null)

  useEffect(() => {
    if (canvas) {
      const dimensionObject = canvas.getActiveObject()
      console.log(dimensionObject)
      const id = dimensionObject.groupId
      const textObj = dimensionObject._objects.filter((obj) => obj.name === 'dimensionLineText' && obj.group.groupId === id)[0]
      if (!textObj) return
      // setBasicLength(parseInt(textObj.text))
      setBasicLength(+dimensionObject.length)
      setSelectedSlope1(dimensionObject.angle1)
      setSelectedSlope2(dimensionObject.angle2)
      setSlopeAble(dimensionObject.slopeAble)
    }

    if (basicSetting.roofAngleSet === 'slope') {
      setOptions(
        Array.from({ length: 21 }).map((_, index) => {
          return {
            name: index * 0.5,
            value: index * 0.5,
          }
        }),
      )
    } else {
      setOptions(
        Array.from({ length: 7 }).map((_, index) => {
          return {
            name: index * 5,
            value: index * 5,
          }
        }),
      )
    }
    return () => {
      setBasicLength(0)
    }
  }, [])

  useEffect(() => {
    // if (!slopeAble) {
    //   const dimensionObject = canvas.getActiveObject()
    //   dimensionObject.set({
    //     angle1: null,
    //     angle2: null,
    //   })
    // }
  }, [slopeAble])

  const handleChangeLength = () => {
    if (canvas) {
      const dimensionObject = canvas.getActiveObject()
      const id = dimensionObject.groupId
      const textObj = dimensionObject._objects.filter((obj) => obj.name === 'dimensionLineText' && obj.group.groupId === id)[0]
      let resultText = +changeLength > 0 ? +changeLength : dimensionObject.length

      if (slopeAble) {
        resultText = !selectedSlope2
          ? calculateLength(resultText, selectedSlope1.value).toFixed(0)
          : calculateLength(resultText, selectedSlope1.value, selectedSlope2.value).toFixed(0)
      }

      textObj.set({
        text: String(resultText),
      })

      dimensionObject.set({
        length: +changeLength > 0 ? +changeLength : dimensionObject.length,
        slopeAble: slopeAble,
        angle1: selectedSlope1,
        angle2: selectedSlope2,
      })
      setBasicLength(resultText)
      setChangeLength('')
      canvas.renderAll()
    }
  }

  const calculateLength = (originalLength, angle, angle1) => {
    const slope1 = basicSetting.roofAngleSet !== 'slope' ? getChonByDegree(angle) : angle
    const slope2 = basicSetting.roofAngleSet !== 'slope' ? getChonByDegree(angle1 ?? 0) : angle1
    if (!angle1) {
      const angleInRadians = slope1 * (Math.PI / 180)
      const result = Math.sqrt(Math.pow(originalLength * Math.tan(angleInRadians), 2) + Math.pow(originalLength, 2))
      console.log(angleInRadians, result)
      return result
    } else {
      const numerator = Math.sqrt(Math.pow(slope1, 2) + 100 + Math.pow((10 * slope1) / slope2, 2)) * originalLength
      const denominator = Math.sqrt(Math.pow((10 * slope1) / slope2, 2) + 100)
      const result = numerator / denominator
      return result
    }
  }

  return (
    <WithDraggable isShow={true} pos={pos}>
      <div className={`modal-pop-wrap xm mount`}>
        <div className="modal-head modal-handle">
          <h1 className="title">{getMessage('contextmenu.display.edit')} </h1>
          <button className="modal-close" onClick={() => closePopup(id)}>
            닫기
          </button>
        </div>
        <div className="modal-body">
          <div className="left-bar modal-handle"></div>
          <div className="right-bar modal-handle"></div>
          <div className="guide">{getMessage('modal.display.edit.info')}</div>
          <div className="mb-box">
            <div className="slope-wrap">
              <div className="outline-form mb15">
                <span className="mr10">{getMessage('modal.display.edit.before.length')}</span>
                <div className="input-grid mr5">
                  <input type="text" className="input-origin block" value={basicLength} readOnly />
                </div>
              </div>
              <div className="mb-box">
                <div className="outline-form">
                  <span className="mr10">{getMessage('modal.display.edit.after.length')}</span>
                  <div className="input-grid mr5">
                    <input
                      type="text"
                      className="input-origin block"
                      defaultValue={''}
                      value={changeLength}
                      onChange={(e) => {
                        console.log(e.target)
                        setChangeLength(e.target.value)
                      }}
                    />
                  </div>
                </div>
              </div>
              <div className="d-check-box pop">
                <input type="checkbox" id="ch99" checked={slopeAble} onChange={() => setSlopeAble(!slopeAble)} />
                <label htmlFor="ch99">{getMessage('modal.display.edit.input.slope')}</label>
              </div>
            </div>
          </div>
          <div className="slope-wrap">
            <div className="warning">{getMessage('modal.display.edit.input.slope')}</div>
            <div className="display-change-wrap">
              <div className="outline-form mb15">
                <span className="mr10">{getMessage('slope')}</span>
                <div className="grid-select mr10">
                  <QSelectBox
                    title={''}
                    options={options}
                    disabled={!slopeAble}
                    value={selectedSlope1}
                    onChange={(e) => setSelectedSlope1(e)}
                    showKey={'name'}
                    sourceKey={'value'}
                    targetKey={'value'}
                  />
                </div>
                <span className="thin">{pitchText}</span>
              </div>
              <div className="outline-form">
                <span className="mr10">{getMessage('slope')}</span>
                <div className="grid-select mr10">
                  <QSelectBox
                    title={''}
                    options={options}
                    disabled={!slopeAble}
                    value={selectedSlope2}
                    onChange={(e) => setSelectedSlope2(e)}
                    showKey={'name'}
                    sourceKey={'value'}
                    targetKey={'value'}
                  />
                </div>
                <span className="thin">{pitchText}</span>
              </div>
            </div>
            <div className="warning">{getMessage('modal.display.edit.input.slope.info')}</div>
          </div>
          <div className="grid-btn-wrap">
            <button className="btn-frame modal act" onClick={handleChangeLength}>
              {getMessage('modal.common.save')}
            </button>
          </div>
        </div>
        <div className="modal-foot modal-handle"></div>
      </div>
    </WithDraggable>
  )
}
