import { useEffect, useState, useReducer, useRef } from 'react'
import { useRecoilValue, useRecoilState } from 'recoil'
import { addedRoofsState } from '@/store/settingAtom'
import { currentCanvasPlanState } from '@/store/canvasAtom'
import { useMessage } from '@/hooks/useMessage'
import QSelectBox from '@/components/common/select/QSelectBox'
import { useModuleSelection } from '@/hooks/module/useModuleSelection'
import ModuleTabContents from './ModuleTabContents'
import { useDebounceValue } from 'usehooks-ts'
import { moduleSelectionDataState } from '@/store/selectedModuleOptions'
import { useCanvasPopupStatusController } from '@/hooks/common/useCanvasPopupStatusController'
import { isObjectNotEmpty } from '@/util/common-utils'

export default function Module({ setTabNum }) {
  const { getMessage } = useMessage()
  const [addedRoofs, setAddedRoofs] = useRecoilState(addedRoofsState) //지붕재 선택
  const [roofTab, setRoofTab] = useState(0) //지붕재 탭

  const {
    moduleSelectionInitParams,
    selectedModules,
    roughnessCodes,
    windSpeedCodes,
    managementState,
    moduleList,
    selectedSurfaceType,
    installHeight,
    standardWindSpeed,
    verticalSnowCover,
    handleChangeModule,
    handleChangeSurfaceType,
    handleChangeWindSpeed,
    handleChangeInstallHeight,
    handleChangeVerticalSnowCover,
  } = useModuleSelection({ addedRoofs })

  const [inputInstallHeight, setInputInstallHeight] = useState()
  const [inputVerticalSnowCover, setInputVerticalSnowCover] = useState()

  const [debouncedInstallHeight] = useDebounceValue(inputInstallHeight, 500)
  const [debouncedVerticalSnowCover] = useDebounceValue(inputVerticalSnowCover, 500)

  const [moduleSelectionData, setModuleSelectionData] = useRecoilState(moduleSelectionDataState) //다음으로 넘어가는 최종 데이터

  const [tempModuleSelectionData, setTempModuleSelectionData] = useReducer((prevState, nextState) => {
    return { ...prevState, ...nextState }
  }, moduleSelectionData)

  useEffect(() => {
    if (installHeight) {
      setInputInstallHeight(installHeight)
    }
    if (verticalSnowCover) {
      setInputVerticalSnowCover(verticalSnowCover)
    }
  }, [installHeight, verticalSnowCover])

  useEffect(() => {
    if (isObjectNotEmpty(tempModuleSelectionData)) {
      if (tempModuleSelectionData.roofConstructions.length > 0) {
        if (tempModuleSelectionData.common.moduleItemId && isObjectNotEmpty(tempModuleSelectionData.module)) {
          //저장된 temp데이터가 지붕재(addedRoofs) 개수와 같으면 모듈 선택 저장
          setModuleSelectionData(tempModuleSelectionData)
          if (tempModuleSelectionData.roofConstructions.length === addedRoofs.length) {
            moduleSelectedDataTrigger(tempModuleSelectionData)
          }
        }
      }
    }
  }, [tempModuleSelectionData])

  useEffect(() => {
    if (debouncedInstallHeight) {
      handleChangeInstallHeight(debouncedInstallHeight)
    }
  }, [debouncedInstallHeight])

  useEffect(() => {
    if (debouncedVerticalSnowCover) {
      handleChangeVerticalSnowCover(debouncedVerticalSnowCover)
    }
  }, [debouncedVerticalSnowCover])

  const moduleData = {
    header: [
      { name: getMessage('module'), width: 150, prop: 'module', type: 'color-box' },
      {
        name: `${getMessage('height')}  (mm)`,
        prop: 'height',
      },
      { name: `${getMessage('width')} (mm)`, prop: 'width' },
      { name: `${getMessage('output')} (W)`, prop: 'output' },
    ],
    rows: [],
  }

  const handleRoofTab = (tab) => {
    setRoofTab(tab)
  }

  const { trigger: moduleSelectedDataTrigger } = useCanvasPopupStatusController(2)

  return (
    <>
      <div className="roof-module-tab2-overflow">
        <div className="module-table-flex-wrap mb10">
          <div className="module-table-box">
            <div className="module-table-inner">
              <div className="outline-form mb10">
                <span className="mr10">{getMessage('modal.module.basic.setting.module.setting')}</span>
                <div className="grid-select">
                  {moduleList && (
                    <QSelectBox
                      options={moduleList}
                      value={moduleSelectionInitParams}
                      targetKey={'moduleItemId'}
                      sourceKey={'itemId'}
                      showKey={'itemNm'}
                      onChange={handleChangeModule}
                    />
                  )}
                </div>
              </div>
              <div className="roof-module-table">
                <table>
                  <thead>
                    <tr>
                      {moduleData.header.map((header) => {
                        return (
                          <th key={header.prop} style={{ width: header.width ? header.width + 'px' : '' }}>
                            {header.name}
                          </th>
                        )
                      })}
                    </tr>
                  </thead>
                  <tbody>
                    {selectedModules &&
                      selectedModules.itemList &&
                      selectedModules.itemList.map((row, index) => (
                        <tr key={index}>
                          <td>
                            <div className="color-wrap">
                              <span className="color-box" style={{ backgroundColor: row.color }}></span>
                              <span className="name">{row.itemNm}</span>
                            </div>
                          </td>
                          <td className="al-r">{Number(row.shortAxis).toFixed(0)}</td>
                          <td className="al-r">{Number(row.longAxis).toFixed(0)}</td>
                          <td className="al-r">{Number(row.wpOut).toFixed(0)}</td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          <div className="module-table-box none-flex">
            <div className="module-table-inner">
              <div className="eaves-keraba-table">
                <div className="eaves-keraba-item">
                  <div className="eaves-keraba-th">{getMessage('modal.module.basic.setting.module.surface.type')}</div>
                  <div className="eaves-keraba-td">
                    <div className="outline-form">
                      <div className="grid-select">
                        {roughnessCodes.length > 0 && (
                          <QSelectBox
                            options={roughnessCodes}
                            value={managementState}
                            targetKey={'surfaceTypeValue'}
                            sourceKey={'clCode'}
                            showKey={'clCodeNm'}
                            onChange={handleChangeSurfaceType}
                          />
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                <div className="eaves-keraba-item">
                  <div className="eaves-keraba-th">{getMessage('modal.module.basic.setting.module.fitting.height')}</div>
                  <div className="eaves-keraba-td">
                    <div className="outline-form">
                      <div className="grid-select mr10">
                        <input
                          type="text"
                          className="input-origin block"
                          value={inputInstallHeight}
                          onChange={(e) => setInputInstallHeight(e.target.value)}
                        />
                      </div>
                      <span className="thin">m</span>
                    </div>
                  </div>
                </div>
                <div className="eaves-keraba-item">
                  <div className="eaves-keraba-th">{getMessage('modal.module.basic.setting.module.standard.wind.speed')}</div>
                  <div className="eaves-keraba-td">
                    <div className="outline-form">
                      <div className="grid-select mr10">
                        {windSpeedCodes.length > 0 && managementState && (
                          <QSelectBox
                            title={''}
                            options={windSpeedCodes}
                            value={managementState}
                            targetKey={'standardWindSpeedId'}
                            sourceKey={'clCode'}
                            showKey={'clCodeNm'}
                            onChange={handleChangeWindSpeed}
                          />
                        )}
                      </div>
                      <span className="thin">m/s</span>
                    </div>
                  </div>
                </div>
                <div className="eaves-keraba-item">
                  <div className="eaves-keraba-th">{getMessage('modal.module.basic.setting.module.standard.snowfall.amount')}</div>
                  <div className="eaves-keraba-td">
                    <div className="outline-form">
                      <div className="grid-select mr10">
                        <input
                          type="text"
                          className="input-origin block"
                          value={inputVerticalSnowCover}
                          onChange={(e) => setInputVerticalSnowCover(e.target.value)}
                        />
                      </div>
                      <span className="thin">cm</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="module-table-box mb10">
          <div className="module-box-tab">
            {addedRoofs &&
              addedRoofs.map((roof, index) => (
                <button key={index} className={`module-btn ${roofTab === index ? 'act' : ''}`} onClick={() => (roof ? handleRoofTab(index) : null)}>
                  {roof !== undefined ? `屋根材${index + 1}` : '-'}
                </button>
              ))}
          </div>
          {addedRoofs &&
            addedRoofs.map((roof, index) => (
              <div style={{ display: roofTab === index ? 'block' : 'none' }} key={index}>
                <ModuleTabContents
                  key={index}
                  tabIndex={index}
                  addRoof={roof}
                  setAddedRoofs={setAddedRoofs}
                  roofTab={roofTab}
                  tempModuleSelectionData={tempModuleSelectionData}
                  setTempModuleSelectionData={setTempModuleSelectionData}
                />
              </div>
            ))}
        </div>
        <div className="module-bottom">
          <div className="module-table-box ">
            <div className="warning-guide">
              <div className="warning">
                {getMessage('modal.module.basic.setting.module.setting.info1')}
                <br />
                {getMessage('modal.module.basic.setting.module.setting.info2')}
              </div>
            </div>
          </div>
          {/* 설정 오류시 노출 */}
        </div>
      </div>
    </>
  )
}
