import { useEffect, useState, useRef } from 'react'
import { useRecoilValue } from 'recoil'
import { canvasSettingState, pitchSelector, pitchTextSelector } from '@/store/canvasAtom'
import { useMessage } from '@/hooks/useMessage'
import { useMasterController } from '@/hooks/common/useMasterController'
import { useCommonCode } from '@/hooks/common/useCommonCode'
import { moduleSelectionInitParamsState, selectedModuleState } from '@/store/selectedModuleOptions'
import { isObjectNotEmpty } from '@/util/common-utils'
import QSelectBox from '@/components/common/select/QSelectBox'

export default function ModuleTabContents({
  addRoof,
  roofTab,
  moduleCommonSelectionData,
  moduleConstructionSelectionData,
  setModuleSelectionData,
  tempModuleSelectionData,
  setTempModuleSelectionData,
}) {
  const { getMessage } = useMessage()
  const canvasSetting = useRecoilValue(canvasSettingState) //캔버스 기본 셋팅
  const [roofMaterial, setRoofMaterial] = useState(addRoof) //지붕재`
  const globalPitchText = useRecoilValue(pitchTextSelector) //피치 텍스트

  const { findCommonCode } = useCommonCode()
  const [raftCodes, setRaftCodes] = useState([]) //가대 목록
  const [trestleList, setTrestleList] = useState([])
  const [constMthdList, setConstMthdList] = useState([])
  const [roofBaseList, setRoofBaseList] = useState([])
  const [constructionList, setConstructionList] = useState([{}]) //공법 목록

  const [selectedRaftBase, setSelectedRaftBase] = useState({}) //선택된 가대
  const [selectedTrestle, setSelectedTrestle] = useState({}) //선택된 가대
  const [selectedConstMthd, setSelectedConstMthd] = useState({}) //선택된 공법
  const [selectedRoofBase, setSelectedRoofBase] = useState({}) //선택된 지붕밑바탕
  const [selectedConstruction, setSelectedConstruction] = useState({}) //선택된 공법
  const [constructionListParams, setConstructionListParams] = useState({})

  const [trestleParams, setTrestleParams] = useState({}) //서까래, 가대메이커,공법,지붕밑바탕 관련  api호출 파라메터
  const [constructionParams, setConstructionParams] = useState({}) //공법 관련  api호출 파라메터
  const [roofBaseParams, setRoofBaseParams] = useState({}) //지붕밑바탕 관련  api호출 파라메터

  const moduleSelectionInitParams = useRecoilValue(moduleSelectionInitParamsState) //모듈 기본 데이터 ex) 면조도, 높이등등

  const { getTrestleList, getConstructionList } = useMasterController()

  const constructionRef = useRef([])
  const [cvrYn, setCvrYn] = useState('N')
  const [snowGdPossYn, setSnowGdPossYn] = useState('N')

  const [cvrChecked, setCvrChecked] = useState(false)
  const [snowGdChecked, setSnowGdChecked] = useState(false)

  const [isExistData, setIsExistData] = useState(false)

  //서까래간격 변경
  const handleChangeRaftBase = (option) => {
    setSelectedRaftBase(option)
    setTrestleParams({ ...trestleParams, raftBaseCd: option.clCode })

    setTrestleList([]) //가대메이커
    setConstMthdList([]) //공법 초기화
    setRoofBaseList([]) //지붕밑바탕 초기화
  }

  //가대메이커 변경
  const handleChangeTrestle = (option) => {
    setSelectedTrestle(option) //선택값  저장
    setConstructionParams({ ...trestleParams, trestleMkrCd: option.trestleMkrCd, constMthdCd: '', roofBaseCd: '' })
  }

  //공법 변경
  const handleChangeConstMthd = (option) => {
    setSelectedConstMthd(option) //선택된값 저장
    setRoofBaseParams({ ...trestleParams, trestleMkrCd: selectedTrestle.trestleMkrCd, constMthdCd: option.constMthdCd, roofBaseCd: '' })
  }

  //지붕밑바탕변경
  const handleChangeRoofBase = (option) => {
    // if (option) {
    setConstructionListParams({
      ...moduleSelectionInitParams,
      ...roofBaseParams,
      roofBaseCd: option.roofBaseCd,
      inclCd: addRoof.pitch,
    })
    setSelectedRoofBase(option)
  }

  const getModuleOptionsListData = async (params) => {
    const optionsList = await getTrestleList(params)

    if (optionsList.data.length > 0) {
      if (optionsList.data[0].trestleMkrCd && optionsList.data[0].constMthdCd === null) {
        setTrestleList(optionsList.data)
        if (isExistData) {
          setSelectedTrestle({ ...moduleConstructionSelectionData.trestle })
        } else {
          setConstMthdList([])
          setRoofBaseList([])
        }
      }

      if (optionsList.data[0].trestleMkrCd && optionsList.data[0].constMthdCd && optionsList.data[0].roofBaseCd === null) {
        setConstMthdList(optionsList.data)
        if (isExistData) {
          setSelectedConstMthd({ ...moduleConstructionSelectionData.trestle })
        } else {
          setRoofBaseList([])
        }
      }

      if (optionsList.data[0].trestleMkrCd && optionsList.data[0].constMthdCd && optionsList.data[0].roofBaseCd) {
        setRoofBaseList(optionsList.data)
        if (isExistData) {
          setSelectedRoofBase({ ...moduleConstructionSelectionData.trestle })
        }
      }
    }
  }

  const getConstructionListData = async (params) => {
    if (params.trestleMkrCd && params.constMthdCd && params.roofBaseCd) {
      const optionsList = await getConstructionList(params)
      setConstructionList(optionsList.data)
    }
  }

  const handleConstruction = (index) => {
    const isPossibleIndex = constructionRef.current
      .map((el, i) => (el.classList.contains('white') || el.classList.contains('blue') ? i : -1))
      .filter((index) => index !== -1)

    isPossibleIndex.forEach((index) => {
      if (constructionRef.current[index].classList.contains('blue')) {
        constructionRef.current[index].classList.remove('blue')
        constructionRef.current[index].classList.add('white')
      }
    })
    constructionRef.current[index].classList.remove('white')
    constructionRef.current[index].classList.add('blue')

    const selectedConstruction = constructionList[index]
    selectedConstruction.roofIndex = roofTab
    selectedConstruction.setupCover = false //처마력바 설치 여부
    selectedConstruction.setupSnowCover = false //눈막이금구 설치 여부
    selectedConstruction.selectedIndex = index

    setCvrYn(selectedConstruction.cvrYn)
    setSnowGdPossYn(selectedConstruction.snowGdPossYn)
    setSelectedConstruction(selectedConstruction)
  }

  useEffect(() => {
    if (isObjectNotEmpty(selectedRoofBase) && isObjectNotEmpty(selectedConstruction)) {
      const newRoofConstructions = {
        roofIndex: roofTab,
        addRoof: addRoof,
        trestle: selectedRoofBase,
        construction: selectedConstruction,
      }
      const index = tempModuleSelectionData.roofConstructions.findIndex((obj) => obj.roofIndex === roofTab)

      if (index > -1) {
        const newArray = [
          ...tempModuleSelectionData.roofConstructions.slice(0, index),
          newRoofConstructions,
          ...tempModuleSelectionData.roofConstructions.slice(index + 1),
        ]
        setTempModuleSelectionData({ roofConstructions: newArray })
      } else {
        setTempModuleSelectionData({ roofConstructions: [...tempModuleSelectionData.roofConstructions, { ...newRoofConstructions }] })
      }
    }
  }, [selectedConstruction])

  const handleCvrChecked = () => {
    setCvrChecked(!cvrChecked)
  }

  const handleSnowGdChecked = () => {
    setSnowGdChecked(!snowGdChecked)
  }

  useEffect(() => {
    setSelectedConstruction({ ...selectedConstruction, setupCover: cvrChecked })
  }, [cvrChecked])

  useEffect(() => {
    setSelectedConstruction({ ...selectedConstruction, setupSnowCover: snowGdChecked })
  }, [snowGdChecked])

  useEffect(() => {
    if (isExistData) {
      setConstructionListParams({
        ...moduleSelectionInitParams,
        ...roofBaseParams,
        roofBaseCd: selectedRoofBase.roofBaseCd,
        inclCd: addRoof.pitch,
      })
    }
  }, [selectedRoofBase])

  useEffect(() => {
    if (isExistData && constructionList.length > 0) {
      const selectedIndex = moduleConstructionSelectionData.construction.selectedIndex
      handleConstruction(selectedIndex)
    }
  }, [constructionList])

  useEffect(() => {
    // 202600 경사도
    const raftCodeList = findCommonCode('203800')
    //서까래 코드
    raftCodeList.forEach((obj) => {
      obj.name = obj.clCodeNm
      obj.id = obj.clCode
    })
    setRaftCodes(raftCodeList)
  }, [])

  useEffect(() => {
    //물건 상세의 데이터를 가지고 초기화 데이터를 만든다
    if (
      moduleSelectionInitParams.illuminationTp &&
      moduleSelectionInitParams.instHt &&
      moduleSelectionInitParams.stdSnowLd &&
      moduleSelectionInitParams.stdWindSpeed
    ) {
      const isModuleLoaded = moduleSelectionInitParams.hasOwnProperty('moduleTpCd') //모듈컬럼이 있으면 모듈을 변경했다는 내용
      if (isModuleLoaded) {
        setTrestleParams({ moduleTpCd: moduleSelectionInitParams.moduleTpCd, roofMatlCd: addRoof.roofMatlCd, raftBaseCd: addRoof.raftBaseCd })
        setConstructionList([])

        if (isObjectNotEmpty(moduleConstructionSelectionData)) {
          setConstructionParams({ ...moduleConstructionSelectionData.trestle, constMthdCd: '', roofBaseCd: '' })
          setRoofBaseParams({ ...moduleConstructionSelectionData.trestle, roofBaseCd: '' })
          setCvrChecked(moduleConstructionSelectionData.construction.setupCover)
          setSnowGdChecked(moduleConstructionSelectionData.construction.setupSnowCover)
          setIsExistData(true)
        }
      }
    }

    setTempModuleSelectionData({ common: moduleSelectionInitParams })
  }, [moduleSelectionInitParams])

  useEffect(() => {
    if (isObjectNotEmpty(trestleParams)) {
      getModuleOptionsListData(trestleParams)
    }
  }, [trestleParams])

  useEffect(() => {
    if (isObjectNotEmpty(constructionParams)) {
      getModuleOptionsListData(constructionParams)
    }
  }, [constructionParams])

  useEffect(() => {
    if (isObjectNotEmpty(roofBaseParams)) {
      getModuleOptionsListData(roofBaseParams)
    }
  }, [roofBaseParams])

  useEffect(() => {
    if (isObjectNotEmpty(constructionListParams)) {
      getConstructionListData(constructionListParams)
    }
  }, [constructionListParams])

  useEffect(() => {
    if (isObjectNotEmpty(tempModuleSelectionData)) {
      setModuleSelectionData(tempModuleSelectionData)
    }
  }, [tempModuleSelectionData])

  return (
    <>
      <div className="module-table-inner">
        <div className="module-table-flex-wrap tab2">
          <div className="module-flex-item">
            <div className="module-flex-item-tit">
              {getMessage('modal.module.basic.setting.module.roof.material')}：{roofMaterial.nameJp}（
              {addRoof.roofAngleSet === 'slope' ? roofMaterial.pitch : roofMaterial.angle}
              {globalPitchText}）
            </div>
            <div className="eaves-keraba-table">
              <div className="eaves-keraba-item">
                <div className="eaves-keraba-th">マンドンピッチ</div>
                <div className="eaves-keraba-td">
                  <div className="grid-select">
                    <QSelectBox
                      options={raftCodes}
                      value={addRoof}
                      sourceKey={'clCode'}
                      targetKey={'raftBaseCd'}
                      showKey={'clCodeNm'}
                      disabled={roofMaterial.raftAuth === 'R' ? true : false}
                      onChange={handleChangeRaftBase}
                    />
                  </div>
                </div>
              </div>
              <div className="eaves-keraba-item">
                {roofMaterial && ['C'].includes(roofMaterial.lenAuth) && (
                  <>
                    <div className="eaves-keraba-th">L</div>
                    <div className="eaves-keraba-td">
                      <div className="keraba-flex">
                        <div className="outline-form">
                          <div className="grid-select">
                            <input
                              type="text"
                              className="input-origin block"
                              value={roofMaterial.lenBase}
                              disabled={roofMaterial.lenAuth === 'R' ? true : false}
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  </>
                )}
                {roofMaterial && ['C', 'R'].includes(roofMaterial.raftAuth) && (
                  <>
                    <div className="eaves-keraba-th">{getMessage('modal.module.basic.setting.module.rafter.margin')}</div>
                    <div className="eaves-keraba-td">
                      <div className="grid-select">
                        {raftCodes.length > 0 && (
                          <QSelectBox
                            options={raftCodes}
                            value={addRoof}
                            sourceKey={'clCode'}
                            targetKey={'raftBaseCd'}
                            showKey={'clCodeNm'}
                            disabled={roofMaterial.raftAuth === 'R' ? true : false}
                            onChange={handleChangeRaftBase}
                          />
                        )}
                      </div>
                    </div>
                  </>
                )}
                {roofMaterial && ['C', 'R'].includes(roofMaterial.roofPchAuth) && (
                  <>
                    <div className="eaves-keraba-th">{getMessage('modal.module.basic.setting.module.rafter.margin')}</div>
                    <div className="eaves-keraba-td">
                      <div className="keraba-flex">
                        <div className="outline-form">
                          <span>垂木の間隔</span>
                          <div className="grid-select">
                            <input
                              type="text"
                              className="input-origin block"
                              value={roofMaterial.hajebichi}
                              disabled={roofMaterial.roofPchAuth === 'R' ? true : false}
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  </>
                )}
              </div>
              <div className="eaves-keraba-item">
                <div className="eaves-keraba-th">{getMessage('modal.module.basic.setting.module.trestle.maker')}</div>
                <div className="eaves-keraba-td">
                  <div className="grid-select">
                    {trestleList && (
                      <QSelectBox
                        title={getMessage('selectbox.title')}
                        options={trestleList}
                        value={selectedTrestle}
                        sourceKey={'trestleMkrCd'}
                        targetKey={'trestleMkrCd'}
                        showKey={'trestleMkrCdNm'}
                        onChange={handleChangeTrestle}
                      />
                    )}
                  </div>
                </div>
              </div>
              <div className="eaves-keraba-item">
                <div className="eaves-keraba-th">{getMessage('modal.module.basic.setting.module.construction.method')}</div>
                <div className="eaves-keraba-td">
                  <div className="grid-select">
                    {constMthdList && (
                      <QSelectBox
                        title={getMessage('selectbox.title')}
                        options={constMthdList}
                        value={selectedConstMthd}
                        sourceKey={'constMthdCd'}
                        targetKey={'constMthdCd'}
                        showKey={'constMthdCdNm'}
                        onChange={handleChangeConstMthd}
                      />
                    )}
                  </div>
                </div>
              </div>
              <div className="eaves-keraba-item">
                <div className="eaves-keraba-th">{getMessage('modal.module.basic.setting.module.under.roof')}</div>
                <div className="eaves-keraba-td">
                  <div className="grid-select">
                    {roofBaseList && (
                      <QSelectBox
                        title={getMessage('selectbox.title')}
                        options={roofBaseList}
                        value={selectedRoofBase}
                        sourceKey={'roofBaseCd'}
                        targetKey={'roofBaseCd'}
                        showKey={'roofBaseCdNm'}
                        onChange={handleChangeRoofBase}
                      />
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className="module-flex-item non-flex">
            <div className="flex-item-btn-wrap">
              <button
                className={`btn-frame roof ${isObjectNotEmpty(constructionList[0]) && constructionList[0].constPossYn === 'Y' ? 'white' : ''}`}
                ref={(el) => (constructionRef.current[0] = el)}
                onClick={() => (isObjectNotEmpty(constructionList[0]) && constructionList[0].constPossYn === 'Y' ? handleConstruction(0) : null)}
              >
                標準施工(Ⅰ)
              </button>
              <button
                className={`btn-frame roof ${isObjectNotEmpty(constructionList[3]) && constructionList[3].constPossYn === 'Y' ? 'white' : ''}`}
                ref={(el) => (constructionRef.current[3] = el)}
                onClick={() => (isObjectNotEmpty(constructionList[3]) && constructionList[3].constPossYn === 'Y' ? handleConstruction(3) : null)}
              >
                多設施工
              </button>
              <button
                className={`btn-frame roof ${isObjectNotEmpty(constructionList[1]) && constructionList[1].constPossYn === 'Y' ? 'white' : ''}`}
                ref={(el) => (constructionRef.current[1] = el)}
                onClick={() => (isObjectNotEmpty(constructionList[1]) && constructionList[1].constPossYn === 'Y' ? handleConstruction(1) : null)}
              >
                標準施工
              </button>
              <button
                className={`btn-frame roof ${isObjectNotEmpty(constructionList[4]) && constructionList[4].constPossYn === 'Y' ? 'white' : ''}`}
                ref={(el) => (constructionRef.current[4] = el)}
                onClick={() => (isObjectNotEmpty(constructionList[4]) && constructionList[4].constPossYn === 'Y' ? handleConstruction(4) : null)}
              >
                多設施工（II）
              </button>
              <button
                className={`btn-frame roof ${isObjectNotEmpty(constructionList[2]) && constructionList[2].constPossYn === 'Y' ? 'white' : ''}`}
                ref={(el) => (constructionRef.current[2] = el)}
                onClick={() => (isObjectNotEmpty(constructionList[2]) && constructionList[2].constPossYn === 'Y' ? handleConstruction(2) : null)}
              >
                強化施工
              </button>
            </div>
            <div className="grid-check-form">
              <div className="d-check-box pop">
                <input
                  type="checkbox"
                  id={`ch01_${roofTab}`}
                  disabled={cvrYn === 'N' ? true : false}
                  defaultChecked={cvrChecked}
                  onChange={handleCvrChecked}
                />
                <label htmlFor={`ch01_${roofTab}`}>{getMessage('modal.module.basic.setting.module.eaves.bar.fitting')}</label>
              </div>
              <div className="d-check-box pop">
                <input
                  type="checkbox"
                  id={`ch02_${roofTab}`}
                  disabled={snowGdPossYn === 'N' ? true : false}
                  defaultChecked={snowGdChecked}
                  onChange={handleSnowGdChecked}
                />
                <label htmlFor={`ch02_${roofTab}`}>{getMessage('modal.module.basic.setting.module.blind.metal.fitting')}</label>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  )
}
