import { useRecoilState } from 'recoil'
import { settingModalFirstOptionsState } from '@/store/settingAtom'
import { useMessage } from '@/hooks/useMessage'
import React, { useEffect, useState } from 'react'
import { get } from '@/lib/Axios'

export default function FirstOption() {
  const [objectNo] = useState('test123240912001') // 이후 삭제 필요
  const [settingsModalOptions, setSettingModalOptions] = useRecoilState(settingModalFirstOptionsState)
  const { option1, option2 } = settingsModalOptions
  const { getMessage } = useMessage()

  const [isFetched, setIsFetched] = useState(false) // 조회 여부 상태

  // 데이터를 최초 한 번만 조회
  useEffect(() => {
    console.log('FirstOption useEffect 실행')
    if (!isFetched) {
      // 조회가 안 되었을 때만 fetchSettings 실행
      fetchSettings()
    }
  }, [isFetched]) // isFetched 상태가 변할 때마다 확인

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

      const options1 = [
        'assignDisplay',
        'drawDisplay',
        'gridDisplay',
        'charDisplay',
        'flowDisplay',
        'hallwayDimenDisplay',
        'actualDimenDisplay',
        'noDimenDisplay',
        'trestleDisplay',
        'coordiDisplay',
        'drawConverDisplay',
      ]
      const option1 = settingsModalOptions.option1.map((item, index) => ({ ...item, selected: res[options1[index]] }))

      const options2 = ['onlyBorder', 'lineHatch', 'allPainted']
      const option2 = settingsModalOptions.option2.map((item, index) => ({ ...item, selected: res[options2[index]] }))

      // 데이터 설정
      setSettingModalOptions({
        option1,
        option2,
      })

      setIsFetched(true) // 조회가 완료되면 isFetched를 true로 설정
    } catch (error) {
      console.error('Data fetching error:', error)
    }
  }

  const onClickOption = (option) => {
    option.selected = !option.selected

    setSettingModalOptions({ option1, option2 })
  }

  return (
    <>
      <div className="modal-check-btn-wrap">
        <h3 className="check-wrap-title light">{getMessage('modal.canvas.setting.first.option.info')}</h3>
        <div className="flex-check-box for2">
          {settingsModalOptions?.option1?.map((item) => (
            <button key={item.id} className={`check-btn ${item.selected ? 'act' : ''}`} onClick={(e) => onClickOption(item)}>
              <span className="check-area"></span>
              <span className="title-area">{getMessage(item.name)}</span>
            </button>
          ))}
        </div>
      </div>
      <div className="modal-check-btn-wrap">
        <h3 className="check-wrap-title">{getMessage('modal.canvas.setting.first.option.display')}</h3>
        <div className="flex-check-box for-line">
          {settingsModalOptions?.option2?.map((item) => (
            <button key={item.id} className={`check-btn ${item.selected ? 'act' : ''}`} onClick={(e) => onClickOption(item)}>
              <span className="check-area"></span>
              <span className="title-area">{getMessage(item.name)}</span>
            </button>
          ))}
        </div>
      </div>
    </>
  )
}
