import { useState, useEffect } from 'react'
import { useMessage } from '@/hooks/useMessage'
import QSelectBox from '@/components/common/select/QSelectBox'
import { useModuleTabContents } from '@/hooks/module/useModuleTabContents'
import { useRecoilValue } from 'recoil'
import { ANGLE_TYPE, currentAngleTypeSelector } from '@/store/canvasAtom'

export default function ModuleTabContents({ tabIndex, addRoof, setAddedRoofs, roofTab, tempModuleSelectionData, setTempModuleSelectionData }) {
  const { getMessage } = useMessage()
  const [roofMaterial, setRoofMaterial] = useState(addRoof) //지붕재`
  const currentAngleType = useRecoilValue(currentAngleTypeSelector)

  const {
    raftCodes,
    trestleList,
    constMthdList,
    roofBaseList,
    constructionList,
    globalPitchText,
    selectedRaftBase,
    selectedTrestle,
    selectedConstMthd,
    selectedRoofBase,
    constructionRef,
    cvrYn,
    cvrChecked,
    snowGdPossYn,
    snowGdChecked,
    lengthBase,
    hajebichi,
    lengthRef,
    hajebichiRef,
    handleHajebichiAndLength,
    handleChangeRaftBase,
    handleChangeTrestle,
    handleChangeConstMthd,
    handleChangeRoofBase,
    handleConstruction,
    handleCvrChecked,
    handleSnowGdChecked,
  } = useModuleTabContents({ tabIndex, addRoof, setAddedRoofs, roofTab, tempModuleSelectionData, setTempModuleSelectionData })

  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}（
              {currentAngleType === ANGLE_TYPE.SLOPE ? roofMaterial.pitch : roofMaterial.angle}
              {globalPitchText}）
            </div>
            <div className="eaves-keraba-table">
              <div className="eaves-keraba-item">
                {roofMaterial && ['C'].includes(roofMaterial.lenAuth) && (
                  <>
                    <div className="eaves-keraba-th">L</div>
                    <div className="eaves-keraba-td">
                      <div className="grid-select">
                        <input
                          type="text"
                          className="input-origin block"
                          value={lengthBase}
                          onChange={(e) => handleHajebichiAndLength(e, 'length')}
                          disabled={roofMaterial.lenAuth === 'R' ? true : false}
                          ref={lengthRef}
                        />
                      </div>
                    </div>
                  </>
                )}
              </div>
              <div className="eaves-keraba-item">
                {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={selectedRaftBase}
                            sourceKey={'clCode'}
                            targetKey={'clCode'}
                            showKey={'clCodeNm'}
                            disabled={roofMaterial.raftAuth === 'R' ? true : false}
                            onChange={handleChangeRaftBase}
                          />
                        )}
                      </div>
                    </div>
                  </>
                )}
              </div>
              <div className="eaves-keraba-item">
                {roofMaterial && ['C', 'R'].includes(roofMaterial.roofPchAuth) && (
                  <>
                    <div className="eaves-keraba-th">{getMessage('modal.module.basic.setting.module.hajebichi')}</div>
                    <div className="eaves-keraba-td">
                      <div className="grid-select">
                        <input
                          type="text"
                          className="input-origin block"
                          disabled={roofMaterial.roofPchAuth === 'R' ? true : false}
                          onChange={(e) => handleHajebichiAndLength(e, 'hajebichi')}
                          value={hajebichi}
                          ref={hajebichiRef}
                        />
                      </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={'trestleMkrCdJp'}
                        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={'constMthdCdJp'}
                        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={'roofBaseCdJp'}
                        onChange={handleChangeRoofBase}
                      />
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className="module-flex-item non-flex">
            <div className="flex-item-btn-wrap">
              {/* 2026-06-05 공법 버튼을 배열 인덱스 대신 constTp로 매핑 — API 응답 항목 추가/순서변경(예: 標準施工(Ⅱ) WORK_LV_ID_-2) 시 인덱스 밀림 방지. 운영(구 API)엔 -2가 없어 optional 은 데이터 있을 때만 렌더 */}
              {[
                // [표시순서변경 2026-06-17] 標準(Ⅱ) 를 標準(Ⅰ) 앞으로 — 사용자 요청
                { constTp: 'WORK_LV_ID_-2', label: '標準施工(Ⅱ)', optional: true },
                { constTp: 'WORK_LV_ID_-1', label: '標準施工(Ⅰ)' },
                { constTp: 'WORK_LV_ID_1', label: '標準施工' },
                { constTp: 'WORK_LV_ID_3', label: '強化施工' },
                { constTp: 'WORK_LV_ID_4', label: '多設施工' },
                { constTp: 'WORK_LV_ID_5', label: '多設施工（II）' },
              ].map(({ constTp, label, optional }) => {
                const index = constructionList.findIndex((c) => c.constTp === constTp)
                const item = index > -1 ? constructionList[index] : null
                if (optional && !item) return null
                const enabled = item && item.constPossYn === 'Y'
                return (
                  <button
                    key={constTp}
                    className={`btn-frame roof ${enabled ? 'white' : ''}`}
                    ref={(el) => {
                      if (index > -1) constructionRef.current[index] = el
                    }}
                    onClick={() => (enabled ? handleConstruction(index) : null)}
                  >
                    {label}
                  </button>
                )
              })}
            </div>
            <div className="grid-check-form-block">
              <div className="d-check-box pop">
                <input
                  type="checkbox"
                  id={`ch01_${tabIndex}`}
                  disabled={cvrYn !== 'Y'}
                  checked={cvrYn === 'Y' && (cvrChecked ?? true)}
                  onChange={handleCvrChecked}
                />
                <label htmlFor={`ch01_${tabIndex}`}>{getMessage('modal.module.basic.setting.module.eaves.bar.fitting')}</label>
              </div>
              <div className="d-check-box pop">
                <input
                  type="checkbox"
                  id={`ch02_${tabIndex}`}
                  disabled={snowGdPossYn === 'N' ? true : false}
                  checked={snowGdChecked || false}
                  onChange={handleSnowGdChecked}
                />
                <label htmlFor={`ch02_${tabIndex}`}>{getMessage('modal.module.basic.setting.module.blind.metal.fitting')}</label>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  )
}
