import WithDraggable from '@/components/common/draggable/WithDraggable'
import QSelectBox from '@/components/common/select/QSelectBox'
import { useEffect, useState } from 'react'
import { useMessage } from '@/hooks/useMessage'
import { canvasState } from '@/store/canvasAtom'
import { useRecoilValue } from 'recoil'
import { onlyNumberInputChange } from '@/util/input-utils'
import { usePopup } from '@/hooks/usePopup'
import { useCanvasSetting } from '@/hooks/option/useCanvasSetting'
import { useSwal } from '@/hooks/useSwal'

const TYPE = {
  DOT: 'DOT',
  LINE: 'LINE',
}

export default function DotLineGrid(props) {
  // const [modalOption, setModalOption] = useRecoilState(modalState); //modal 열림닫힘 state
  //const interval = useRecoilValue(dotLineIntervalSelector)
  const { id, setIsShow, pos = { x: 840, y: -815 }, isConfig = false, settingsData, setSettingsData, settingsDataSave, setSettingsDataSave } = props
  const canvas = useRecoilValue(canvasState)

  const { getMessage } = useMessage()
  const { closePopup } = usePopup()
  const { swalFire } = useSwal()

  const [selectOption, setSelectOption] = useState()

  const { SelectOptions, currentSetting, setCurrentSetting, dotLineGridSettingState, setSettingModalGridOptions, setDotLineGridSettingState } =
    useCanvasSetting()

  const [copyCurrentSetting, setCopyCurrentSetting] = useState({ ...currentSetting })

  // 데이터를 최초 한 번만 조회
  useEffect(() => {
    console.log('DotLineGrid useEffect 실행')

    setSettingsDataSave({ ...settingsData })

    // dimension 값에 맞는 옵션을 선택
    const matchedOption = SelectOptions.find((option) => option.value == currentSetting.INTERVAL.dimension)
    setSelectOption(matchedOption)

    return () => {
      setSettingModalGridOptions((prev) => {
        const newSettingOptions = [...prev]
        newSettingOptions[1].selected = false
        return [...newSettingOptions]
      })
    }
  }, [])

  const HandleClickClose = () => {
    // setClose(true)
    // setTimeout(() => {
    //   setModalOption({ ...modalOption, gridoption: false })
    //   setClose(false)
    // }, 180)
  }

  const handleCheckBoxChange = (e) => {
    const { value, checked } = e.target
    setCopyCurrentSetting((prev) => {
      return {
        ...prev,
        [value]: checked,
      }
    })
  }

  const handleSave = async () => {
    /*if (!currentSetting.DOT && !currentSetting.LINE) {
      swalFire({ text: '배치할 그리드를 설정해주세요.' })
      return
    }*/

    setDotLineGridSettingState((prev) => {
      return {
        ...prev,
        INTERVAL: {
          type: copyCurrentSetting.INTERVAL.type,
          horizontalInterval: copyCurrentSetting.INTERVAL.horizontalInterval,
          verticalInterval: copyCurrentSetting.INTERVAL.verticalInterval,
          ratioInterval: copyCurrentSetting.INTERVAL.ratioInterval,
          dimension: copyCurrentSetting.INTERVAL.dimension,
        },
        DOT: copyCurrentSetting.DOT,
        LINE: copyCurrentSetting.LINE,
      }
      //setDotLineGridSettingState({ ...currentSetting })
    })

    setSettingsData({
      ...settingsData,
      INTERVAL: {
        type: copyCurrentSetting.INTERVAL.type,
        horizontalInterval: copyCurrentSetting.INTERVAL.horizontalInterval,
        verticalInterval: copyCurrentSetting.INTERVAL.verticalInterval,
        ratioInterval: copyCurrentSetting.INTERVAL.ratioInterval,
        dimension: copyCurrentSetting.INTERVAL.dimension,
      },
      DOT: copyCurrentSetting.DOT,
      LINE: copyCurrentSetting.LINE,
    })

    setCurrentSetting({ ...copyCurrentSetting })

    setIsShow(false)
    closePopup(id, isConfig)
  }

  const handleRadioChange = (e) => {
    const { value, name, checked, selected } = e.target

    setCopyCurrentSetting((prev) => {
      return {
        ...prev,
        INTERVAL: {
          ...prev.INTERVAL,
          type: Number(value),
        },
      }
    })
  }

  const changeInput = (value, e) => {
    const { name } = e.target
    setCopyCurrentSetting((prev) => {
      return {
        ...prev,
        INTERVAL: {
          ...prev.INTERVAL,
          [name]: value,
        },
      }
    })
  }

  const changeDimension = (result) => {
    const { value } = result
    setSelectOption(result)
    setCopyCurrentSetting((prev) => {
      return {
        ...prev,
        INTERVAL: {
          ...prev.INTERVAL,
          dimension: value,
        },
      }
    })
  }

  // 초기화
  const reset = () => {
    /*canvas
      ?.getObjects()
      .filter((obj) => obj.name === 'lineGrid')
      .forEach((obj) => canvas?.remove(obj))
    canvas
      ?.getObjects()
      .filter((obj) => obj.name === 'dotGrid')
      .forEach((obj) => canvas?.remove(obj))
*/
    // resetDotLineGridSetting()
    setCopyCurrentSetting({
      INTERVAL: {
        type: 2, // 1: 가로,세로 간격 수동, 2: 비율 간격
        ratioInterval: 910,
        verticalInterval: 910,
        horizontalInterval: 910,
        dimension: 1, // 치수
      },
      DOT: false,
      LINE: false,
    })
    setSelectOption(SelectOptions[0])
  }

  return (
    <WithDraggable isShow={true} pos={pos} className="ssm">
      <WithDraggable.Header
        title={getMessage('modal.canvas.setting.grid.dot.line.setting')}
        onClose={() => {
          setIsShow(false)
          closePopup(id, isConfig)
        }}
      />
      <WithDraggable.Body>
        <div className="grid-check-form">
          <div className="d-check-box pop">
            <input type="checkbox" id="ch01" value={TYPE.DOT} onChange={handleCheckBoxChange} checked={copyCurrentSetting.DOT} />
            <label htmlFor="ch01">{getMessage('modal.canvas.setting.grid.dot.line.setting.dot.display')}</label>
          </div>
          <div className="d-check-box pop">
            <input type="checkbox" id="ch02" value={TYPE.LINE} onChange={handleCheckBoxChange} checked={copyCurrentSetting.LINE} />
            <label htmlFor="ch02">{getMessage('modal.canvas.setting.grid.dot.line.setting.line.display')}</label>
          </div>
        </div>
        <div className="grid-option-wrap">
          <div className="grid-option-box">
            <div className="d-check-radio pop no-text">
              <input
                type="radio"
                name="radio01"
                id="ra01"
                value={1}
                onChange={handleRadioChange}
                checked={(copyCurrentSetting.DOT || copyCurrentSetting.LINE) && copyCurrentSetting.INTERVAL.type === 1}
                readOnly={!copyCurrentSetting.DOT && !copyCurrentSetting.LINE}
              />
              <label htmlFor="ra01"></label>
            </div>
            <div className="grid-input-form">
              <span className="mr10">{getMessage('modal.canvas.setting.grid.dot.line.setting.horizon')}</span>
              <div className="input-grid mr5">
                <input
                  type="text"
                  className="input-origin"
                  name={`horizontalInterval`}
                  value={copyCurrentSetting.INTERVAL.horizontalInterval}
                  onChange={(e) => onlyNumberInputChange(e, changeInput)}
                />
              </div>
              <span>mm</span>
            </div>
            <div className="grid-input-form">
              <span className="mr10">{getMessage('modal.canvas.setting.grid.dot.line.setting.vertical')}</span>
              <div className="input-grid mr5">
                <input
                  type="text"
                  className="input-origin"
                  name={`verticalInterval`}
                  value={copyCurrentSetting.INTERVAL.verticalInterval}
                  onChange={(e) => onlyNumberInputChange(e, changeInput)}
                />
              </div>
              <span>mm</span>
            </div>
          </div>
          <div className="grid-option-box">
            <div className="d-check-radio pop no-text">
              <input
                type="radio"
                name="radio01"
                id="ra02"
                value={2}
                onChange={handleRadioChange}
                checked={(copyCurrentSetting.DOT || copyCurrentSetting.LINE) && copyCurrentSetting.INTERVAL.type === 2}
                readOnly={!copyCurrentSetting.DOT && !copyCurrentSetting.LINE}
              />
              <label htmlFor="ra02"></label>
            </div>
            <div className="grid-input-form">
              <span className="mr10">{getMessage('modal.canvas.setting.grid.dot.line.setting.ratio')}</span>
              <div className="input-grid mr5">
                <input
                  type="text"
                  className="input-origin"
                  name={`ratioInterval`}
                  value={copyCurrentSetting.INTERVAL.ratioInterval}
                  onChange={(e) => onlyNumberInputChange(e, changeInput)}
                />
              </div>
              <span>mm</span>
            </div>
            <div className="grid-select">
              {selectOption && (
                <QSelectBox
                  options={SelectOptions}
                  onChange={changeDimension}
                  value={selectOption}
                  showKey={'name'}
                  targetKey={'id'}
                  sourceKey={'id'}
                />
              )}
            </div>
          </div>
        </div>
        <div className="grid-btn-wrap">
          <button className="btn-frame modal mr5" onClick={reset}>
            {getMessage('modal.canvas.setting.grid.dot.line.setting.reset')}
          </button>
          <button className="btn-frame modal act" onClick={handleSave}>
            {getMessage('modal.canvas.setting.grid.dot.line.setting.save')}
          </button>
        </div>
      </WithDraggable.Body>
    </WithDraggable>
  )
}
