import { useMessage } from '@/hooks/useMessage'
import React, { useEffect, useState } from 'react'
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 { useCanvasSetting } from '@/hooks/option/useCanvasSetting'
import { useRecoilState, useRecoilValue } from 'recoil'
import { fontSelector, globalFontAtom } from '@/store/fontAtom'

export default function SecondOption() {
  const { getMessage } = useMessage()
  const { addPopup, closePopup } = usePopup()
  const [showFontSettingModal, setShowFontSettingModal] = useState(false)
  const [showDimensionLineSettingModal, setShowDimensionLineSettingModal] = useState(false)
  const [showPlanSizeSettingModal, setShowPlanSizeSettingModal] = useState(false)
  const [globalFont, setGlobalFont] = useRecoilState(globalFontAtom)
  const commonFont = useRecoilValue(fontSelector('commonText'))
  const flowFont = useRecoilValue(fontSelector('flowText'))
  const lengthFont = useRecoilValue(fontSelector('lengthText'))
  const circuitNumberTextFont = useRecoilValue(fontSelector('circuitNumberText'))
  const [dimensionId, setDimensionId] = useState(uuidv4())
  const [fontId, setFontId] = useState(uuidv4())
  const [planSizeId, setPlanSizeId] = useState(uuidv4())

  const {
    fetchSettings,
    planSizeSettingMode,
    setPlanSizeSettingMode,
    settingModalSecondOptions,
    setSettingModalSecondOptions,
    adsorptionPointMode,
    setAdsorptionPointMode,
    setAdsorptionRange,
  } = useCanvasSetting()
  const { option3, option4 } = settingModalSecondOptions

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

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

    switch (type) {
      case 'font1': {
        //문자 글꼴변경
        setShowFontSettingModal(true)
        setShowDimensionLineSettingModal(false)
        fontProps.type = 'commonText'
        fontProps.font = commonFont
        fontProps.id = fontId + 1
        addPopup(fontId + 1, 2, <FontSetting {...fontProps} />, true)
        break
      }

      case 'font2': {
        //흐름 방향 글꼴 변경
        setShowFontSettingModal(true)
        setShowDimensionLineSettingModal(false)
        fontProps.type = 'flowText'
        fontProps.font = flowFont
        fontProps.id = fontId + 2
        addPopup(fontId + 2, 2, <FontSetting {...fontProps} />, true)
        break
      }

      case 'font3': {
        //치수 글꼴변경
        setShowFontSettingModal(true)
        setShowDimensionLineSettingModal(false)
        fontProps.type = 'lengthText'
        fontProps.font = lengthFont
        fontProps.id = fontId + 3
        addPopup(fontId + 3, 2, <FontSetting {...fontProps} />, true)
        break
      }

      case 'font4': {
        //회로번호 글꼴변경
        setShowFontSettingModal(true)
        setShowDimensionLineSettingModal(false)
        fontProps.type = 'circuitNumberText'
        fontProps.font = circuitNumberTextFont
        fontProps.id = fontId
        addPopup(fontId, 2, <FontSetting {...fontProps} />, true)
        break
      }

      case 'dimensionLine': {
        //치수선 설정
        if (!showDimensionLineSettingModal) {
          setShowDimensionLineSettingModal(true)
          fontProps.font = {
            fontFamily: '',
            fontWeight: '',
            fontSize: '',
            fontColor: '',
          }
          addPopup(dimensionId, 2, <DimensionLineSetting {...dimensionProps} />, true)
        } else {
          setShowDimensionLineSettingModal(false)
          closePopup(dimensionId)
        }
        break
      }

      case 'planSize': {
        //도면크기 설정
        if (!showPlanSizeSettingModal) {
          fetchSettings() //화면 오픈 시 데이터 조회
          setShowPlanSizeSettingModal(true)
          addPopup(planSizeId, 2, <PlanSizeSetting {...planSizeProps} />, true)
        } else {
          setShowPlanSizeSettingModal(false)
          closePopup(planSizeId, true)
        }
        break
      }
    }
  }

  const handleFontSave = (font) => {
    setGlobalFont((prev) => {
      return {
        ...prev,
        [fontProps.type]: {
          // fontFamily: font.fontFamily.value,
          // fontWeight: font.fontWeight.value,
          // fontSize: font.fontSize.value,
          // fontColor: font.fontColor.value,
          fontFamily: font.fontFamily,
          fontWeight: font.fontWeight,
          fontSize: font.fontSize,
          fontColor: font.fontColor,
        },
        fontFlag: true,
      }
    })
  }

  const fontProps = {
    id: fontId,
    pos: { x: 745, y: 180 },
    setIsShow: setShowFontSettingModal,
    onSave: handleFontSave,
    isConfig: true,
  }

  const dimensionProps = {
    id: dimensionId,
    isShow: showDimensionLineSettingModal,
    setIsShow: setShowDimensionLineSettingModal,
  }

  const planSizeProps = {
    id: planSizeId,
    horizon: planSizeSettingMode.originHorizon,
    vertical: planSizeSettingMode.originVertical,
    isShow: showPlanSizeSettingModal,
    setIsShow: setShowPlanSizeSettingModal,
    pos: { x: 1025, y: 180 },
  }

  const onClickOption = async (item) => {
    //흡착범위 설정(단 건 선택)
    if (
      item.column === 'adsorpRangeSmall' ||
      item.column === 'adsorpRangeSmallSemi' ||
      item.column === 'adsorpRangeMedium' ||
      item.column === 'adsorpRangeLarge'
    ) {
      // option4에서 한 개만 선택 가능하도록 처리
      //const updatedOption4 = option4.map((option) => (option.id === item.id ? { ...option, selected: true } : { ...option, selected: false }))
      const options = settingModalSecondOptions?.option4.map((option4) => {
        option4.selected = option4.id === item.id
        return option4
      })

      setSettingModalSecondOptions({ ...settingModalSecondOptions, option3, option4, fontFlag: true })
    } else if (item === 'adsorpPoint') {
      setAdsorptionPointMode({ ...adsorptionPointMode, adsorptionPoint: !adsorptionPointMode.adsorptionPoint, fontFlag: true })
    }
    //setAdsorptionRange(item.range) //사용여부 확인 필요
    setAdsorptionRange(50)
  }

  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={() => {
              onClickOption('adsorpPoint')
            }}
          >
            <span>{getMessage('modal.canvas.setting.font.plan.absorption.point')}</span>
            <i>{adsorptionPointMode.adsorptionPoint ? 'ON' : 'OFF'}</i>
          </button>
        </div>
      </div>
    </>
  )
}
