import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil'
import { settingModalFirstOptionsState, 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 { adsorptionPointModeState, adsorptionRangeState } from '@/store/canvasAtom'
import DimensionLineSetting from '@/components/floor-plan/modal/setting01/dimensionLine/DimensionLineSetting'
import { usePopup } from '@/hooks/usePopup'
import { v4 as uuidv4 } from 'uuid'
import FontSetting from '@/components/common/font/FontSetting'
import PlanSizeSetting from '@/components/floor-plan/modal/setting01/planSize/PlanSizeSetting'
import { dimensionLineSettingsState } from '@/store/commonUtilsAtom'

export default function SecondOption() {
  const [objectNo, setObjectNo] = useState('test123240912001') // 이후 삭제 필요
  const [settingModalFirstOptions, setSettingModalFirstOptions] = useRecoilState(settingModalFirstOptionsState)
  const [settingModalSecondOptions, setSettingModalSecondOptions] = useRecoilState(settingModalSecondOptionsState)
  const [adsorptionPointMode, setAdsorptionPointMode] = useRecoilState(adsorptionPointModeState)
  const setAdsorptionRange = useSetRecoilState(adsorptionRangeState)

  const { option1, option2, dimensionDisplay } = settingModalFirstOptions
  const { option3, option4 } = settingModalSecondOptions
  const { getMessage } = useMessage()
  const { get, post } = useAxios()
  const { swalFire } = useSwal()
  const { addPopup, closePopup, closePopups } = usePopup()
  const [showFontSettingModal, setShowFontSettingModal] = useState(false)
  const [showDimensionLineSettingModal, setShowDimensionLineSettingModal] = useState(false)
  const [showPlanSizeSettingModal, setShowPlanSizeSettingModal] = useState(false)
  const dimensionSettings = useRecoilValue(dimensionLineSettingsState)

  // 데이터를 최초 한 번만 조회
  useEffect(() => {
    console.log('SecondOption 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) => {
    // option4에서 한 개만 선택 가능하도록 처리
    const updatedOption4 = option4.map((item) =>
      item.id === option.id
        ? { ...item, selected: true }
        : {
            ...item,
            selected: false,
          },
    )

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

    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].option3.map((item) => ({
        //   name: item.id,
        //   name: item.name,
        //   // 필요한 경우 데이터 항목 추가
        // })),
        secondOption2: updatedOption4.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' })
    }
    setAdsorptionRange(option.range)
  }
  let dimensionId = null
  let fontId = null
  let planSizeId = null
  const [pixel, setPixel] = useState(dimensionSettings.pixel)
  const [color, setColor] = useState(dimensionSettings.color)
  const [font, setFont] = useState(null)
  const [fontSize, setFontSize] = useState(dimensionSettings.fontSize)
  const [fontColor, setFontColor] = useState(dimensionSettings.fontColor)

  useEffect(() => {
    dimensionId = uuidv4()
    fontId = uuidv4()
    planSizeId = uuidv4()
  }, [])

  const dimensionProps = {
    color,
    setColor,
    pixel,
    setPixel,
    font,
    setFont,
    fontSize,
    setFontSize,
    fontColor,
    setFontColor,
    id: dimensionId,
    isShow: showDimensionLineSettingModal,
    setIsShow: setShowDimensionLineSettingModal,
  }

  const [horizon, setHorizon] = useState(1600)
  const [vertical, setVertical] = useState(1600)

  const fontProps = {
    id: fontId,
    pos: { x: 745, y: 180 },
    setIsShow: setShowFontSettingModal,
  }
  const planSizeProps = {
    id: planSizeId,
    horizon,
    setHorizon,
    vertical,
    setVertical,
    setIsShow: setShowPlanSizeSettingModal,
    pos: { x: 1025, y: 180 },
  }

  const handlePopup = (type) => {
    setShowPlanSizeSettingModal(false)
    setShowFontSettingModal(false)

    switch (type) {
      case 'dimensionLine':
        if (!showDimensionLineSettingModal) {
          setShowDimensionLineSettingModal(true)
          addPopup(dimensionId, 2, <DimensionLineSetting {...dimensionProps} />)
        } else {
          setShowDimensionLineSettingModal(false)
          closePopup(dimensionId)
        }

        break
      case 'font1': {
        //문자 글꼴변경
        setShowFontSettingModal(true)
        fontProps.type = 'commonText'
        fontProps.id = fontId + 1
        addPopup(fontId + 1, 2, <FontSetting {...fontProps} />)
        break
      }
      case 'font2': {
        //흐름 방향 글꼴 변경
        setShowFontSettingModal(true)
        fontProps.type = 'flowText'
        fontProps.id = fontId + 2
        addPopup(fontId + 2, 2, <FontSetting {...fontProps} />)
        break
      }
      case 'font3': {
        //치수 글꼴변경
        setShowFontSettingModal(true)
        fontProps.type = 'lengthText'
        fontProps.id = fontId + 3
        addPopup(fontId + 3, 2, <FontSetting {...fontProps} />)
        break
      }
      case 'font4': //회로번호 글꼴변경
        setShowFontSettingModal(true)
        fontProps.type = 'circuitNumberText'
        fontProps.id = fontId
        addPopup(fontId, 2, <FontSetting {...fontProps} />)
        break
      case 'planSize':
        setShowPlanSizeSettingModal(true)

        addPopup(planSizeId, 2, <PlanSizeSetting {...planSizeProps} />)
        break
    }
  }

  return (
    <>
      <div className="modal-check-btn-wrap">
        <h3 className="check-wrap-title">{getMessage('modal.canvas.setting.font.plan.edit')}</h3>
        <div className="flex-check-box for2">
          {settingModalSecondOptions &&
            settingModalSecondOptions.option3.map((item) => (
              <button key={item.id} className="arr-btn" onClick={() => handlePopup('font' + item.id)}>
                <span>{getMessage(item.name)}</span>
              </button>
            ))}
        </div>
      </div>
      <div className="modal-check-btn-wrap">
        <h3 className="check-wrap-title">{getMessage('modal.canvas.setting.font.plan.absorption')}</h3>
        <div className="flex-check-box for-line">
          {settingModalSecondOptions &&
            settingModalSecondOptions.option4.map((item) => (
              <button key={item.id} className={`check-btn ${item.selected ? 'act' : ''}`} onClick={() => onClickOption(item)}>
                <span className="check-area"></span>
                <span className="title-area">{getMessage(item.name)}</span>
              </button>
            ))}
        </div>
        <div className="flex-check-box for-line">
          {/*<button className="arr-btn" onClick={() => setShowDimensionLineSettingModal(true)}>*/}
          <button className={`arr-btn ${showDimensionLineSettingModal ? 'act' : ''}`} onClick={() => handlePopup('dimensionLine')}>
            <span>{getMessage('modal.canvas.setting.font.plan.absorption.dimension.line')}</span>
          </button>
          <button className={`arr-btn ${showPlanSizeSettingModal ? 'act' : ''}`} onClick={() => handlePopup('planSize')}>
            <span>{getMessage('modal.canvas.setting.font.plan.absorption.plan.size.setting')}</span>
          </button>
          <button
            className="adsorption-point act"
            onClick={(e) => {
              setAdsorptionPointMode(!adsorptionPointMode)
            }}
          >
            <span>{getMessage('modal.canvas.setting.font.plan.absorption.point')}</span>
            <i>{adsorptionPointMode ? 'ON' : 'OFF'}</i>
          </button>
        </div>
      </div>
    </>
  )
}
