import { forwardRef, useEffect, useState } from 'react'
import { useMessage } from '@/hooks/useMessage'
import { useModuleBasicSetting } from '@/hooks/module/useModuleBasicSetting'
import { checkedModuleState, currentCanvasPlanState, isManualModuleLayoutSetupState, isManualModuleSetupState } from '@/store/canvasAtom'
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil'
import { moduleSelectionDataState, selectedModuleState } from '@/store/selectedModuleOptions'
import { isObjectNotEmpty } from '@/util/common-utils'

const Placement = forwardRef((props, refs) => {
  const { getMessage } = useMessage()
  const [isChidori, setIsChidori] = useState(false)
  const [isChidoriNotAble, setIsChidoriNotAble] = useState(false)

  const [setupLocation, setSetupLocation] = useState('eaves')
  const [isMaxSetup, setIsMaxSetup] = useState('false')
  const [selectedItems, setSelectedItems] = useState({})

  const [selectedModules, setSelectedModules] = useRecoilState(selectedModuleState)

  const setCheckedModules = useSetRecoilState(checkedModuleState)
  const moduleSelectionData = useRecoilValue(moduleSelectionDataState)
  const { makeModuleInitArea } = useModuleBasicSetting(3)

  const [isMultiModule, setIsMultiModule] = useState(false)

  //언마운트시 버튼 초기화
  const setIsManualModuleSetup = useSetRecoilState(isManualModuleSetupState)
  const setIsManualModuleLayoutSetup = useSetRecoilState(isManualModuleLayoutSetupState)

  //모듈 배치면 생성
  useEffect(() => {
    if (moduleSelectionData) {
      //1개라도 치도리 불가가 있으면 치도리 불가
      const isChidroriValue = moduleSelectionData.roofConstructions.some((item) => item.construction.plvrYn === 'N')
      if (isChidroriValue) {
        setIsChidoriNotAble(true)
      }
      makeModuleInitArea(moduleSelectionData)
    }

    return () => {
      setIsManualModuleSetup(false)
      setIsManualModuleLayoutSetup(false)
    }
  }, [])

  //최초 지입시 체크
  useEffect(() => {
    if (isObjectNotEmpty(moduleSelectionData)) {
      //두번째 선택한 데이터가를 기반으로 세번째 선택을 체크한다
      if (moduleSelectionData.roofConstructions.length > 0 && moduleSelectionData.module.itemList.length > 0) {
        let initCheckedModule = {}
        moduleSelectionData.module.itemList.forEach((obj, index) => {
          if (index === 0) {
            initCheckedModule = { [obj.itemId]: true }
          } else {
            initCheckedModule = { ...initCheckedModule, [obj.itemId]: true }
          }
        })
        setSelectedItems(initCheckedModule)
        setSelectedModules(moduleSelectionData.module)
        props.setLayoutSetup(moduleSelectionData.module.itemList.map((item) => ({ moduleId: item.itemId, col: 0, row: 0 })))
        props.layoutSetupRef.current = moduleSelectionData.module.itemList.map((item) => ({ moduleId: item.itemId, col: 0, row: 0 }))
      }

      //모듈 배치면 생성
      if (isObjectNotEmpty(moduleSelectionData.module) && moduleSelectionData.module.itemList.length > 1) {
        setIsMultiModule(true)
      }
    }
  }, [moduleSelectionData])

  //체크된 모듈 데이터
  useEffect(() => {
    if (isObjectNotEmpty(selectedItems) && isObjectNotEmpty(selectedModules)) {
      const checkedModuleIds = Object.keys(selectedItems).filter((key) => selectedItems[key])
      const moduleArray = selectedModules.itemList.filter((item) => {
        return checkedModuleIds.includes(item.itemId)
      })
      setCheckedModules(moduleArray)
    }
  }, [selectedItems, selectedModules])

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

  const handleChangeChidori = (e) => {
    const bool = e.target.value === 'true' ? true : false
    setIsChidori(bool)
    refs.isChidori.current = e.target.value
  }

  const handleSetupLocation = (e) => {
    setSetupLocation(e.target.value)
    refs.setupLocation.current = e.target.value
  }

  const handleMaxSetup = (e) => {
    if (e.target.checked) {
      setIsMaxSetup('true')
      refs.isMaxSetup.current = 'true'
    } else {
      setIsMaxSetup('false')
      refs.isMaxSetup.current = 'false'
    }
  }

  //체크된 모듈 아이디 추출
  const handleSelectedItem = (e) => {
    setSelectedItems({ ...selectedItems, [e.target.name]: e.target.checked })
  }

  const handleLayoutSetup = (e, itemId, index) => {
    const newLayoutSetup = [...props.layoutSetup]
    newLayoutSetup[index] = { ...newLayoutSetup[index], moduleId: itemId, [e.target.name]: Number(e.target.value) }
    props.setLayoutSetup(newLayoutSetup)
    props.layoutSetupRef.current[index] = { ...props.layoutSetupRef.current[index], moduleId: itemId, [e.target.name]: Number(e.target.value) }
  }

  return (
    <>
      <div className="module-table-flex-wrap mb10">
        <div className="module-table-box">
          <div className="module-table-inner">
            <div className="roof-module-table">
              <table>
                <thead>
                  <tr>
                    {moduleData.header.map((data) => (
                      <th key={data.prop} style={{ width: data.width ? data.width : '' }}>
                        {data.type === 'check' ? (
                          <div className="d-check-box no-text pop">
                            <input type="checkbox" id="ch01" disabled />
                            <label htmlFor="ch01"></label>
                          </div>
                        ) : (
                          data.name
                        )}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {selectedModules.itemList &&
                    selectedModules.itemList.map((item, index) => (
                      <tr key={index}>
                        <td className="al-c">
                          <div className="d-check-box no-text pop">
                            <input
                              type="checkbox"
                              id={item.itemId}
                              name={item.itemId}
                              checked={selectedItems[item.itemId]}
                              onChange={handleSelectedItem}
                            />
                            <label htmlFor={item.itemId}></label>
                          </div>
                        </td>
                        <td>
                          <div className="color-wrap">
                            <span className="color-box" style={{ backgroundColor: item.color }}></span>
                            <span className="name">{item.itemNm}</span>
                          </div>
                        </td>
                        <td className="al-r">{item.wpOut}</td>
                        <label htmlFor="ra06">행</label>
                        <input
                          type="text"
                          className="input-origin block mr10"
                          name="col"
                          value={props.layoutSetup[index]?.col ?? 1}
                          defaultValue={1}
                          onChange={(e) => handleLayoutSetup(e, item.itemId, index)}
                        />{' '}
                        ×<label htmlFor="ra07">열</label>
                        <input
                          type="text"
                          className="input-origin block"
                          name="row"
                          value={props.layoutSetup[index]?.row ?? 1}
                          defaultValue={1}
                          onChange={(e) => handleLayoutSetup(e, item.itemId, index)}
                        />
                      </tr>
                    ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
        <div className="module-table-box">
          <div className="module-table-inner">
            <div className="self-table-tit">{getMessage('modal.module.basic.setting.module.placement.select.fitting.type')}</div>
            <div className="module-self-table">
              <div className="self-table-item">
                <div className="self-item-th">{getMessage('modal.module.basic.setting.module.placement.waterfowl.arrangement')}</div>
                <div className="self-item-td">
                  <div className="pop-form-radio">
                    <div className="d-check-radio pop">
                      <input
                        type="radio"
                        name="radio01"
                        id="ra01"
                        checked={isChidori}
                        disabled={isChidoriNotAble}
                        value={'true'}
                        onChange={(e) => handleChangeChidori(e)}
                      />
                      <label htmlFor="ra01">{getMessage('modal.module.basic.setting.module.placement.do')}</label>
                    </div>
                    <div className="d-check-radio pop">
                      <input type="radio" name="radio02" id="ra02" checked={!isChidori} value={'false'} onChange={(e) => handleChangeChidori(e)} />
                      <label htmlFor="ra02">{getMessage('modal.module.basic.setting.module.placement.do.not')}</label>
                    </div>
                  </div>
                </div>
              </div>
              <div className="self-table-item">
                <div className="self-item-th">{getMessage('modal.module.basic.setting.module.placement.arrangement.standard')}</div>
                <div className="self-item-td">
                  <div className="pop-form-radio">
                    <div className="d-check-radio pop">
                      <input
                        type="radio"
                        name="radio03"
                        id="ra03"
                        checked={setupLocation === 'center'}
                        value={'center'}
                        onChange={handleSetupLocation}
                        disabled={isMultiModule}
                      />
                      <label htmlFor="ra03">{getMessage('modal.module.basic.setting.module.placement.arrangement.standard.center')}</label>
                    </div>
                    <div className="d-check-radio pop">
                      <input
                        type="radio"
                        name="radio04"
                        id="ra04"
                        checked={setupLocation === 'eaves'}
                        value={'eaves'}
                        onChange={handleSetupLocation}
                      />
                      <label htmlFor="ra04">{getMessage('modal.module.basic.setting.module.placement.arrangement.standard.eaves')}</label>
                    </div>
                    <div className="d-check-radio pop">
                      <input
                        type="radio"
                        name="radio05"
                        id="ra05"
                        checked={setupLocation === 'ridge'}
                        value={'ridge'}
                        onChange={handleSetupLocation}
                        disabled={isMultiModule}
                      />
                      <label htmlFor="ra05">{getMessage('modal.module.basic.setting.module.placement.arrangement.standard.ridge')}</label>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div className="self-table-flx">
              {/* <div className="d-check-box pop">
                <input type="checkbox" id="ch04" checked={isMaxSetup === 'true'} value={'true'} onChange={handleMaxSetup} />
                <label htmlFor="ch04">{getMessage('modal.module.basic.setting.module.placement.maximum')}</label>
              </div> */}
            </div>
          </div>
        </div>
      </div>
    </>
  )
})

export default Placement
