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, dotLineGridSettingState, dotLineIntervalSelector } from '@/store/canvasAtom'
import { useRecoilState, useRecoilValue, useResetRecoilState, useSetRecoilState } from 'recoil'
import { onlyNumberInputChange } from '@/util/input-utils'
import { fabric } from 'fabric'
import { gridColorState } from '@/store/gridAtom'
import { gridDisplaySelector, settingModalGridOptionsState } from '@/store/settingAtom'
import { useAxios } from '@/hooks/useAxios'
import { useSwal } from '@/hooks/useSwal'
import { usePopup } from '@/hooks/usePopup'

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

const defaultDotLineGridSetting = {
  INTERVAL: {
    type: 2, // 1: 가로,세로 간격 수동, 2: 비율 간격
    ratioInterval: 910,
    verticalInterval: 910,
    horizontalInterval: 910,
    dimension: 1, // 치수
  },
  DOT: false,
  LINE: false,
}

export default function DotLineGrid(props) {
  // const [modalOption, setModalOption] = useRecoilState(modalState); //modal 열림닫힘 state
  const [objectNo, setObjectNo] = useState('test123240912001') // 이후 삭제 필요
  const [close, setClose] = useState(false)
  const { id, setIsShow, pos = { x: 840, y: -815 } } = props
  const setSettingModalGridOptions = useSetRecoilState(settingModalGridOptionsState)

  const canvas = useRecoilValue(canvasState)

  const [dotLineGridSetting, setDotLineGridSettingState] = useRecoilState(dotLineGridSettingState)
  const [currentSetting, setCurrentSetting] = useState(
    JSON.stringify(dotLineGridSetting) === JSON.stringify(defaultDotLineGridSetting) ? { ...defaultDotLineGridSetting } : { ...dotLineGridSetting },
  )
  const resetDotLineGridSetting = useResetRecoilState(dotLineGridSettingState)
  const interval = useRecoilValue(dotLineIntervalSelector)

  const { getMessage } = useMessage()
  const { get, post } = useAxios()
  const { swalFire } = useSwal()
  const { closePopup } = usePopup()

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

  const SelectOption = [
    { id: 1, name: getMessage('modal.canvas.setting.grid.dot.line.setting.line.origin'), value: 1 },
    { id: 2, name: '1/2', value: 1 / 2 },
    { id: 3, name: '1/4', value: 1 / 4 },
    { id: 4, name: '1/10', value: 1 / 10 },
  ]
  const [selectOption, setSelectOption] = useState(SelectOption[0])

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

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

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

  // Canvas Grid Setting 조회 및 초기화
  const fetchGridSettings = async () => {
    try {
      const res = await get({ url: `/api/canvas-management/canvas-grid-settings/by-object/${objectNo}` })

      const patternData = {
        INTERVAL: {
          type: res.gridType,
          horizontalInterval: res.gridHorizon,
          verticalInterval: res.gridVertical,
          ratioInterval: res.gridRatio,
        },
        dimension: res.gridDimen,
        DOT: res.dotGridDisplay,
        LINE: res.lineGridDisplay,
      }

      const matchedOption = SelectOption.find((option) => option.value == res.gridDimen)

      // dimension 값에 맞는 옵션을 선택
      setSelectOption(matchedOption)

      // 서버에서 받은 데이터로 상태 업데이트
      setCurrentSetting(patternData)
    } catch (error) {
      console.error('Data fetching error:', error)
    }
  }

  const handleSave = async () => {
    if (!currentSetting.DOT && !currentSetting.LINE) {
      swalFire({ text: '배치할 그리드를 설정해주세요.' })
      return
    }
    try {
      const patternData = {
        objectNo,
        dotGridDisplay: currentSetting.DOT,
        lineGridDisplay: currentSetting.LINE,
        gridType: currentSetting.INTERVAL.type,
        gridHorizon: currentSetting.INTERVAL.horizontalInterval / 10,
        gridVertical: currentSetting.INTERVAL.verticalInterval / 10,
        gridRatio: currentSetting.INTERVAL.ratioInterval / 10,
        gridDimen: currentSetting.INTERVAL.dimension,
      }

      // HTTP POST 요청 보내기
      await post({ url: `/api/canvas-management/canvas-grid-settings`, data: patternData }).then((res) => {
        swalFire({ text: getMessage(res.returnMessage) })
        setDotLineGridSettingState({ ...currentSetting })
        closePopup(id)
      })
    } catch (error) {
      swalFire({ text: getMessage(res.returnMessage), icon: 'error' })
    }
  }

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

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

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

  const changeDimension = (result) => {
    const { value } = result
    setCurrentSetting((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()
    setSelectOption(SelectOption[0])
  }

  return (
    <WithDraggable isShow={true} pos={pos}>
      <div className={`modal-pop-wrap ssm mount`}>
        <div className="modal-head">
          <h1 className="title">{getMessage('modal.canvas.setting.grid.dot.line.setting')}</h1>
          <button
            className="modal-close"
            onClick={() => {
              setIsShow(false)
              closePopup(id)
            }}
          >
            닫기
          </button>
        </div>
        <div className="modal-body">
          <div className="grid-check-form">
            <div className="d-check-box pop">
              <input type="checkbox" id="ch01" value={TYPE.DOT} onChange={handleCheckBoxChange} checked={currentSetting.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={currentSetting.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={(currentSetting.DOT || currentSetting.LINE) && currentSetting.INTERVAL.type === 1}
                  readOnly={!currentSetting.DOT && !currentSetting.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={currentSetting.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={currentSetting.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={(currentSetting.DOT || currentSetting.LINE) && currentSetting.INTERVAL.type === 2}
                  readOnly={!currentSetting.DOT && !currentSetting.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={currentSetting.INTERVAL.ratioInterval}
                    onChange={(e) => onlyNumberInputChange(e, changeInput)}
                  />
                </div>
                <span>mm</span>
              </div>
              <div className="grid-select">
                <QSelectBox options={SelectOption} onChange={changeDimension} value={selectOption} />
              </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>
        </div>
      </div>
    </WithDraggable>
  )
}
