import { forwardRef, useState, useEffect } from 'react'
import { useMessage } from '@/hooks/useMessage'
import { useModuleBasicSetting } from '@/hooks/module/useModuleBasicSetting'
import { canvasState, checkedModuleState } from '@/store/canvasAtom'
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil'
import { POLYGON_TYPE } from '@/common/common'
import { useEvent } from '@/hooks/useEvent'
import { moduleSelectionDataState } from '@/store/selectedModuleOptions'

const PitchPlacement = forwardRef((props, refs) => {
  const { getMessage } = useMessage()
  const [setupLocation, setSetupLocation] = useState('south')
  const canvas = useRecoilValue(canvasState)
  const { initEvent } = useEvent()

  const { selectedModules } = useModuleBasicSetting(3)
  const setCheckedModules = useSetRecoilState(checkedModuleState)
  const moduleSelectionData = useRecoilValue(moduleSelectionDataState) //다음으로 넘어가는 최종 데이터
  const [selectedItems, setSelectedItems] = useState({})
  const { makeModuleInitArea } = useModuleBasicSetting(3)

  useEffect(() => {
    if (moduleSelectionData) {
      makeModuleInitArea(moduleSelectionData)
    }
  }, [])

  useEffect(() => {
    handleChangeSetupLocation()
  }, [setupLocation])

  const handleSelectedItem = (e) => {
    setSelectedItems({ ...selectedItems, [e.target.name]: e.target.checked })
  }

  //체크된 모듈 데이터
  useEffect(() => {
    const checkedModuleIds = Object.keys(selectedItems).filter((key) => selectedItems[key])
    if (selectedModules.length < 1) return // null 오류 차단 로직 추가
    const moduleArray = selectedModules.itemList.filter((item) => {
      return checkedModuleIds.includes(item.itemId)
    })
    setCheckedModules(moduleArray)
  }, [selectedItems])

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

  const handleChangeSetupLocation = () => {
    if (setupLocation === 'south') {
      canvas.getObjects().forEach((obj) => obj.name === 'flatExcretaLine' && canvas.remove(obj))
      return null
    } else {
      const moduleSetupSurfaces = canvas?.getObjects().filter((obj) => obj.name === POLYGON_TYPE.MODULE_SETUP_SURFACE) //모듈설치면를 가져옴
      moduleSetupSurfaces.forEach((surface, index) => {
        const excretaLine = surface.lines

        excretaLine.forEach((line) => {
          line.set({
            stroke: '#642EFB',
            strokeWidth: 3,
            surfaceId: surface.surfaceId,
            name: 'flatExcretaLine',
          })
          canvas.add(line)

          line.on('selected', () => {
            excretaLine.forEach((obj) => obj.set({ stroke: '#642EFB', isSelected: false }))
            if (!line.isSelected) {
              line.set({ stroke: 'red', isSelected: true })
            } else {
              line.set({ stroke: '#642EFB', isSelected: false })
            }
          })
        })
      })
    }
  }

  useEffect(() => {
    if (!moduleSelectionData.module) return // null 오류 차단 로직 추가
    if (moduleSelectionData && 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)
    }
  }, [])

  return (
    <>
      <div className="hexagonal-flex-wrap">
        <div className="module-table-box ">
          <div className="module-table-inner">
            <div className="roof-module-table">
              <table>
                <thead>
                  <tr>
                    <th style={{ width: '70px' }}>
                      <div className="d-check-box no-text pop">
                        <input type="checkbox" id="ch01" disabled />
                        <label htmlFor="ch01"></label>
                      </div>
                    </th>
                    <th>{getMessage('module')}</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>
                      </tr>
                    ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
        <div className="module-table-box non-flex">
          <div className="module-table-inner">
            <div className="roof-module-table">
              <table>
                <thead>
                  <tr>
                    <th>{getMessage('modal.module.basic.setting.pitch.module.placement.standard.setting')}</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>
                      <div className="hexagonal-radio-wrap">
                        <div className="d-check-radio pop mb10">
                          <input
                            type="radio"
                            name="radio01"
                            id="ra01"
                            value={'south'}
                            defaultChecked={setupLocation === 'south'}
                            onClick={handleSetupLocation}
                          />
                          <label htmlFor="ra01">{getMessage('modal.module.basic.setting.pitch.module.placement.standard.setting.south')}</label>
                        </div>
                        <div className="d-check-radio pop">
                          <input
                            type="radio"
                            name="radio01"
                            id="ra02"
                            value={'excreta'}
                            defaultChecked={setupLocation === 'excreta'}
                            onClick={handleSetupLocation}
                          />
                          <label htmlFor="ra02">{getMessage('modal.module.basic.setting.pitch.module.placement.standard.setting.select')}</label>
                        </div>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </>
  )
})

export default PitchPlacement
