import { useState, useEffect } from 'react'
import { useRecoilState } from 'recoil'
import { useMessage } from '@/hooks/useMessage'
import QSelectBox from '@/components/common/select/QSelectBox'
import { useMasterController } from '@/hooks/common/useMasterController'
import { moduleSelectionDataState, selectedModuleState } from '@/store/selectedModuleOptions'
import { useCanvasPopupStatusController } from '@/hooks/common/useCanvasPopupStatusController'
import { isObjectNotEmpty } from '@/util/common-utils'

export default function PitchModule({}) {
  const { getMessage } = useMessage()
  const { getModuleTypeItemList } = useMasterController()
  const [moduleList, setModuleList] = useState([])
  const [selectedModules, setSelectedModules] = useRecoilState(selectedModuleState) //선택된 모듈
  const [moduleSelectionData, setModuleSelectionData] = useRecoilState(moduleSelectionDataState) //다음으로 넘어가는 최종 데이터

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

  const getModuleData = async (roofsIds) => {
    const list = await getModuleTypeItemList(roofsIds)
    if (list.data.length > 0) {
      //selectbox에 이름을 넣는다
      list.data.forEach((item) => {
        item.name = item.itemNm
      })
      //셀렉트박스 데이터 초기화
      setModuleList(list.data)
    }
  }

  useEffect(() => {
    getModuleData(['FLAT_ROOF'])
  }, [])

  const handleChangeModule = (option) => {
    //선택된 모듈
    setSelectedModules(option) //선택값 저장
    setModuleSelectionData({
      ...moduleSelectionData,
      module: option,
    })
    moduleSelectedDataTrigger({
      ...moduleSelectionData,
      module: option,
    })
  }

  useEffect(() => {
    if (isObjectNotEmpty(moduleSelectionData.module) && moduleList.length > 0) {
      handleChangeModule(moduleSelectionData.module)
    }
  }, [moduleList])

  const { trigger: moduleSelectedDataTrigger } = useCanvasPopupStatusController(2)

  return (
    <>
      <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
                  title={getMessage('selectbox.title')}
                  options={moduleList}
                  value={selectedModules}
                  targetKey={'itemId'}
                  sourceKey={'itemId'}
                  showKey={'itemNm'}
                  onChange={handleChangeModule}
                />
              )}
            </div>
          </div>
          <div className="roof-module-table">
            <table>
              <thead>
                <tr>
                  {moduleData.header.map((data) => (
                    <th key={data.prop} style={{ width: data.width ? data.width : '' }}>
                      {data.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>{Number(row.shortAxis).toFixed(0)}</td>
                      <td>{Number(row.longAxis).toFixed(0)}</td>
                      <td>{Number(row.wpOut).toFixed(0)}</td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </>
  )
}
