import { useRecoilState, useRecoilValue } from 'recoil'
import { settingModalSecondOptionsState } from '@/store/settingAtom'
import { useMessage } from '@/hooks/useMessage'
import React, { useEffect, useState } from 'react'
import { useAxios } from '@/hooks/useAxios'
import { useSwal } from '@/hooks/useSwal'
import { useFirstOption } from '@/hooks/option/useFirstOption'
import { setSurfaceShapePattern } from '@/util/canvas-util'
import { canvasState } from '@/store/canvasAtom'
import { POLYGON_TYPE } from '@/common/common'

export default function FirstOption() {
  const [objectNo, setObjectNo] = useState('test123240912001') // 이후 삭제 필요
  const { settingModalFirstOptions, setSettingModalFirstOptions } = useFirstOption()
  const [settingModalSecondOptions, setSettingModalSecondOptions] = useRecoilState(settingModalSecondOptionsState)
  const { option1, option2, dimensionDisplay } = settingModalFirstOptions
  const { option3, option4 } = settingModalSecondOptions
  const { getMessage } = useMessage()
  const { get, post } = useAxios()
  const { swalFire } = useSwal()
  const canvas = useRecoilValue(canvasState)

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

  // Canvas Setting 조회 및 초기화
  const fetchSettings = async () => {
    try {
      const res = await get({ url: `/api/canvas-management/canvas-settings/by-object/${objectNo}` })
      const optionData1 = settingModalFirstOptions.option1.map((item) => ({ ...item, selected: res[item.column] }))
      const optionData2 = settingModalFirstOptions.option2.map((item) => ({ ...item, selected: res[item.column] }))
      const optionData5 = settingModalFirstOptions.dimensionDisplay.map((item) => ({ ...item, selected: res[item.column] }))
      const optionData3 = settingModalSecondOptions.option3.map((item) => ({ ...item }))
      const optionData4 = settingModalSecondOptions.option4.map((item) => ({ ...item, selected: res[item.column] }))

      // 데이터 설정
      setSettingModalFirstOptions({
        option1: optionData1,
        option2: optionData2,
        dimensionDisplay: optionData5,
      })

      setSettingModalSecondOptions({
        option3: optionData3,
        option4: optionData4,
      })
    } catch (error) {
      console.error('Data fetching error:', error)
    }
  }

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

    setSettingModalFirstOptions({ option1, option2, dimensionDisplay })
    setSettingModalSecondOptions({ option3, option4 })

    try {
      // 서버에 전송할 데이터
      const dataToSend = {
        firstOption1: option1.map((item) => ({
          column: item.column,
          selected: item.selected,
        })),
        firstOption2: option2.map((item) => ({
          column: item.column,
          selected: item.selected,
        })),
        firstOption3: dimensionDisplay.map((item) => ({
          column: item.column,
          selected: item.selected,
        })),
        // secondOption1: secondOptions[0].option1.map((item) => ({
        //   name: item.id,
        //   name: item.name,
        //   // 필요한 경우 데이터 항목 추가
        // })),
        secondOption2: option4.map((item) => ({
          column: item.column,
          selected: item.selected,
        })),
      }

      const patternData = {
        objectNo,
        //디스플레이 설정(다중)
        allocDisplay: dataToSend.firstOption1[0].selected,
        outlineDisplay: dataToSend.firstOption1[1].selected,
        gridDisplay: dataToSend.firstOption1[2].selected,
        lineDisplay: dataToSend.firstOption1[3].selected,
        wordDisplay: dataToSend.firstOption1[4].selected,
        circuitNumDisplay: dataToSend.firstOption1[5].selected,
        flowDisplay: dataToSend.firstOption1[6].selected,
        trestleDisplay: dataToSend.firstOption1[7].selected,
        totalDisplay: dataToSend.firstOption1[8].selected,
        //차수 표시(다건)
        corridorDimension: dataToSend.firstOption3[0].selected,
        realDimension: dataToSend.firstOption3[1].selected,
        noneDimension: dataToSend.firstOption3[2].selected,
        //화면 표시(다중)
        onlyBorder: dataToSend.firstOption2[0].selected,
        lineHatch: dataToSend.firstOption2[1].selected,
        allPainted: dataToSend.firstOption2[2].selected,
        //흡착범위 설정(단건)
        adsorpRangeSmall: dataToSend.secondOption2[0].selected,
        adsorpRangeSmallSemi: dataToSend.secondOption2[1].selected,
        adsorpRangeMedium: dataToSend.secondOption2[2].selected,
        adsorpRangeLarge: dataToSend.secondOption2[3].selected,
      }

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

  const onClickOnlyOne = async (item) => {
    //화면 표시
    if (item.column === 'onlyBorder' || item.column === 'lineHatch' || item.column === 'allPainted') {
      const options2 = settingModalFirstOptions?.option2.map((option2) => {
        option2.selected = option2.id === item.id
        return option2
      })

      const polygons = canvas?.getObjects().filter((obj) => obj.name === POLYGON_TYPE.ROOF)

      polygons.forEach((polygon) => {
        setSurfaceShapePattern(polygon, item.column)
      })

      //치수 표시
    } else {
      const options = settingModalFirstOptions?.dimensionDisplay.map((option) => {
        option.selected = option.id === item.id
        return option
      })
    }

    setSettingModalFirstOptions({ option1, option2, dimensionDisplay })

    try {
      // 서버에 전송할 데이터
      const dataToSend = {
        firstOption1: option1.map((item) => ({
          column: item.column,
          selected: item.selected,
        })),
        firstOption2: option2.map((item) => ({
          column: item.column,
          selected: item.selected,
        })),
        firstOption3: dimensionDisplay.map((item) => ({
          column: item.column,
          selected: item.selected,
        })),
        // secondOption1: secondOptions[0].option1.map((item) => ({
        //   name: item.id,
        //   name: item.name,
        //   // 필요한 경우 데이터 항목 추가
        // })),
        secondOption2: option4.map((item) => ({
          column: item.column,
          selected: item.selected,
        })),
      }

      const patternData = {
        objectNo,
        //디스플레이 설정(다중)
        allocDisplay: dataToSend.firstOption1[0].selected,
        outlineDisplay: dataToSend.firstOption1[1].selected,
        gridDisplay: dataToSend.firstOption1[2].selected,
        lineDisplay: dataToSend.firstOption1[3].selected,
        wordDisplay: dataToSend.firstOption1[4].selected,
        circuitNumDisplay: dataToSend.firstOption1[5].selected,
        flowDisplay: dataToSend.firstOption1[6].selected,
        trestleDisplay: dataToSend.firstOption1[7].selected,
        totalDisplay: dataToSend.firstOption1[8].selected,
        //차수 표시(다건)
        corridorDimension: dataToSend.firstOption3[0].selected,
        realDimension: dataToSend.firstOption3[1].selected,
        noneDimension: dataToSend.firstOption3[2].selected,
        //화면 표시(다중)
        onlyBorder: dataToSend.firstOption2[0].selected,
        lineHatch: dataToSend.firstOption2[1].selected,
        allPainted: dataToSend.firstOption2[2].selected,
        //흡착범위 설정(단건)
        adsorpRangeSmall: dataToSend.secondOption2[0].selected,
        adsorpRangeSmallSemi: dataToSend.secondOption2[1].selected,
        adsorpRangeMedium: dataToSend.secondOption2[2].selected,
        adsorpRangeLarge: dataToSend.secondOption2[3].selected,
      }

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

  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">
          {settingModalFirstOptions &&
            settingModalFirstOptions.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.dimension')}</h3>
        <div className="flex-check-box for-line">
          {settingModalFirstOptions &&
            settingModalFirstOptions.dimensionDisplay.map((item) => (
              <button key={item.id} className={`check-btn ${item.selected ? 'act' : ''}`} onClick={(e) => onClickOnlyOne(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">
          {settingModalFirstOptions &&
            settingModalFirstOptions.option2.map((item) => (
              <button key={item.id} className={`check-btn ${item.selected ? 'act' : ''}`} onClick={(e) => onClickOnlyOne(item)}>
                <span className="check-area"></span>
                <span className="title-area">{getMessage(item.name)}</span>
              </button>
            ))}
        </div>
      </div>
    </>
  )
}
