import { useEffect, useState, useReducer } from 'react'
import { useRecoilValue, useRecoilState } from 'recoil'
import { addedRoofsState } from '@/store/settingAtom'
import { canvasSettingState, pitchSelector } 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 { useDebounceCallback, useDebounceValue } from 'usehooks-ts'
import { moduleSelectionDataState } from '@/store/selectedModuleOptions'

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

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

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

  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(() => {
    handleChangeInstallHeight(debouncedInstallHeight)
  }, [debouncedInstallHeight])

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

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

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

  useEffect(() => {}, [roofTab])

  useEffect(() => {
    console.log('moduleSelectionData', moduleSelectionData)
  }, [])

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

  return (
    <>
      <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={'moduleTpCd'}
                    sourceKey={'itemTp'}
                    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.itemList &&
                    selectedModules.itemList.map((row) => (
                      <>
                        <tr>
                          <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="module-table-tit">{getMessage('modal.module.basic.setting.module.stuff.info')}</div>
            <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" style={{ width: '95.77px', flex: 'none' }}>
                      {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">mm</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">mm</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}
                index={index}
                addRoof={roof}
                roofTab={index}
                moduleCommonSelectionData={moduleSelectionData.common}
                moduleConstructionSelectionData={moduleSelectionData.roofConstructions[index]}
                setModuleSelectionData={setModuleSelectionData}
                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 className="reset-word">※ 施工方法が選択できません。 基準風速または基準積雪量を確認してください。</div>
      </div>
    </>
  )
}
