import { forwardRef, use, useContext, useEffect, useImperativeHandle, useState } from 'react'
import { useMessage } from '@/hooks/useMessage'
import { useOrientation } from '@/hooks/module/useOrientation'
import { getDegreeInOrientation } from '@/util/canvas-util'
import { numberCheck } from '@/util/common-utils'
import { useCanvasPopupStatusController } from '@/hooks/common/useCanvasPopupStatusController'
import { addedRoofsState, basicSettingState } from '@/store/settingAtom'
import { useRecoilState, useRecoilValue } from 'recoil'
import QSelectBox from '@/components/common/select/QSelectBox'
import { moduleSelectionDataState } from '@/store/selectedModuleOptions'

export const Orientation = forwardRef((props, ref) => {
  const { getMessage } = useMessage()
  const [hasAnglePassivity, setHasAnglePassivity] = useState(false)
  const basicSetting = useRecoilValue(basicSettingState)
  const [addedRoofs, setAddedRoofs] = useRecoilState(addedRoofsState) //지붕재 선택
  const [roofTab, setRoofTab] = useState(0) //지붕재 탭
  const {
    roofs,
    setRoofs,
    tabNum,
    setTabNum,
    compasDeg,
    setCompasDeg,
    moduleSelectionInitParams,
    selectedModules,
    roughnessCodes,
    windSpeedCodes,
    managementState,
    setManagementState,
    moduleList,
    moduleSelectionData,
    setModuleSelectionData,
    setSelectedModules,
    selectedSurfaceType,
    setSelectedSurfaceType,
    installHeight,
    setInstallHeight,
    standardWindSpeed,
    setStandardWindSpeed,
    verticalSnowCover,
    setVerticalSnowCover,
    orientationTrigger,
    nextStep,
    currentCanvasPlan,
    loginUserState,
    updateObjectDataApi,
  } = props
  const [inputCompasDeg, setInputCompasDeg] = useState(compasDeg ?? 0)
  const [inputInstallHeight, setInputInstallHeight] = useState('0')
  const [inputVerticalSnowCover, setInputVerticalSnowCover] = useState('0')
  const [inputRoughness, setInputRoughness] = useState(selectedSurfaceType)
  const [inputStandardWindSpeed, setInputStandardWindSpeed] = useState(standardWindSpeed)
  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' },
    ],
  }

  useEffect(() => {
    if (selectedSurfaceType) {
      console.log(roughnessCodes, selectedSurfaceType)
      setInputRoughness(roughnessCodes.find((code) => code.clCode === moduleSelectionData.common.illuminationTp))
    }
  }, [selectedSurfaceType])

  useEffect(() => {
    if (standardWindSpeed) setInputStandardWindSpeed(windSpeedCodes.find((code) => code.clCode === moduleSelectionData.common.stdWindSpeed))
  }, [standardWindSpeed])

  useEffect(() => {
    if (managementState?.installHeight && managementState?.installHeight) {
      console.log('🚀 ~ useEffect ~ managementState:', managementState)
      setSelectedSurfaceType(roughnessCodes.find((code) => code.clCode === managementState?.surfaceTypeValue))
      setInputInstallHeight(managementState?.installHeight)
      setStandardWindSpeed(windSpeedCodes.find((code) => code.clCode === managementState?.standardWindSpeedId))
      setInputVerticalSnowCover(managementState?.verticalSnowCover)
    }
  }, [managementState])

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

  useImperativeHandle(ref, () => ({
    handleNextStep,
  }))

  const handleNextStep = () => {
    if (isComplete()) {
      const common = {
        illuminationTp: inputRoughness.clCode,
        illuminationTpNm: inputRoughness.clCodeNm,
        instHt: inputInstallHeight,
        stdWindSpeed: inputStandardWindSpeed.clCode,
        stdSnowLd: inputVerticalSnowCover,
        saleStoreNorthFlg: managementState?.saleStoreNorthFlg,
        moduleTpCd: selectedModules.itemTp,
        moduleItemId: selectedModules.itemId,
      }
      setCompasDeg(inputCompasDeg)
      setInstallHeight(inputInstallHeight)
      setVerticalSnowCover(inputVerticalSnowCover)
      setSelectedSurfaceType(inputRoughness)
      setStandardWindSpeed(inputStandardWindSpeed)
      nextStep()
      setManagementState({
        ...managementState,
        installHeight: inputInstallHeight,
        verticalSnowCover: inputVerticalSnowCover,
        standardWindSpeedId: inputStandardWindSpeed.clCode,
        surfaceType: inputRoughness.clCodeNm,
        surfaceTypeValue: inputRoughness.clCode,
      })
      setModuleSelectionData({
        ...moduleSelectionData,
        module: {
          ...selectedModules,
        },
      })
      orientationTrigger({
        compasDeg: inputCompasDeg,
        common: common,
        module: {
          ...selectedModules,
        },
      })
      updateObjectDataApi({
        objectNo: currentCanvasPlan.objectNo, //오브젝트_no
        standardWindSpeedId: inputStandardWindSpeed.clCode, //기준풍속코드
        verticalSnowCover: inputVerticalSnowCover, //적설량
        surfaceType: inputRoughness.clCodeNm, //면조도구분
        installHeight: inputInstallHeight, //설치높이
        userId: loginUserState.userId, //작성자아아디
      })
      setTabNum(2)
    }
  }

  const checkDegree = (e) => {
    if (e === '-0' || e === '-') {
      setInputCompasDeg('-')
      return
    }
    if (e === '0-') {
      setCompasDeg('-0')
      return
    }
    if (Number(e) >= -180 && Number(e) <= 180) {
      if (numberCheck(Number(e))) {
        setCompasDeg(Number(e))
      }
    } else {
      setCompasDeg(compasDeg)
    }
  }

  const isComplete = () => {
    if (basicSetting && basicSetting.roofSizeSet !== '3') {
      if (inputInstallHeight <= 0) {
        return false
      }

      if (+inputVerticalSnowCover <= 0) {
        return false
      }

      if (!inputStandardWindSpeed) return false
      if (!inputRoughness) return false
    }

    return true
  }

  const handleChangeModule = (e) => {
    const newRoofs = addedRoofs.map((roof) => {
      return {
        ...roof,
        lengthBase: null,
        raftBaseCd: null,
        trestleMkrCd: null,
        constMthdCd: null,
        constTp: null,
        roofBaseCd: null,
        ridgeMargin: null,
        kerabaMargin: null,
        eavesMargin: null,
        roofPchBase: null,
        cvrYn: 'N',
        snowGdPossYn: 'N',
        cvrChecked: false,
        snowGdChecked: false,
      }
    })
    setRoofs(newRoofs)
    setSelectedModules(e)
  }

  return (
    <>
      <div className="properties-setting-wrap">
        <div className="outline-wrap">
          <div className="roof-module-inner">
            <div className="compas-wrapper">
              <div className="guide">{getMessage('modal.module.basic.setting.orientation.setting.info')}</div>
              <div className="roof-module-compas">
                <div className="compas-box">
                  <div className="compas-box-inner">
                    {Array.from({ length: 180 / 15 }).map((dot, index) => (
                      <div
                        key={index}
                        className={`circle ${getDegreeInOrientation(inputCompasDeg) === -1 * (-15 * index + 180) || (index === 0 && inputCompasDeg >= 172 && index === 0 && inputCompasDeg <= 180) || (inputCompasDeg === -180 && index === 0) ? 'act' : ''}`}
                        onClick={() => {
                          if (index === 0) {
                            setInputCompasDeg(180)
                            return
                          }
                          setInputCompasDeg(-1 * (-15 * index + 180))
                        }}
                      >
                        {index === 0 && <i>180°</i>}
                        {index === 6 && <i>-90°</i>}
                      </div>
                    ))}
                    {Array.from({ length: 180 / 15 }).map((dot, index) => (
                      <div
                        key={index}
                        className={`circle ${inputCompasDeg !== 180 && getDegreeInOrientation(inputCompasDeg) === 15 * index ? 'act' : ''}`}
                        onClick={() => setInputCompasDeg(15 * index)}
                      >
                        {index === 0 && <i>0°</i>}
                        {index === 6 && <i>90°</i>}
                      </div>
                    ))}
                    <div className="compas">
                      <div className="compas-arr" style={{ transform: `rotate(${getDegreeInOrientation(inputCompasDeg)}deg)` }}></div>
                    </div>
                  </div>
                </div>
              </div>
              <div className="center-wrap">
                <div className="outline-form">
                  <div className="d-check-box pop mr10">
                    <input type="checkbox" id="ch99" checked={hasAnglePassivity} onChange={() => setHasAnglePassivity(!hasAnglePassivity)} />
                    <label htmlFor="ch99">{getMessage('modal.module.basic.setting.orientation.setting.angle.passivity')}</label>
                  </div>
                  <div className="input-grid mr10" style={{ width: '60px' }}>
                    <input
                      type="text"
                      className="input-origin block"
                      value={inputCompasDeg}
                      readOnly={!hasAnglePassivity}
                      placeholder={0}
                      onChange={(e) => checkDegree(e.target.value)}
                    />
                  </div>
                  <span className="thin">°</span>
                  <span className="thin">（ -180 〜 180 ）</span>
                </div>
              </div>
            </div>
            <div className="compas-table-wrap">
              <div className="compas-table-box mb10">
                <div className="outline-form mb10">
                  <span>{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={(e) => handleChangeModule(e)}
                      />
                    )}
                  </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>
                      {Array.from({ length: 2 }).map((_, index) => {
                        return selectedModules && selectedModules?.itemList && selectedModules?.itemList?.length >= index + 1 ? (
                          <tr key={index}>
                            <td>
                              <div className="color-wrap">
                                <span
                                  className="color-box"
                                  style={{
                                    backgroundColor: selectedModules.itemList[index].color,
                                  }}
                                ></span>
                                <span className="name">{selectedModules.itemList[index].itemNm}</span>
                              </div>
                            </td>
                            <td className="al-r">{Number(selectedModules.itemList[index].shortAxis).toFixed(0)}</td>
                            <td className="al-r">{Number(selectedModules.itemList[index].longAxis).toFixed(0)}</td>
                            <td className="al-r">{Number(selectedModules.itemList[index].wpOut).toFixed(0)}</td>
                          </tr>
                        ) : (
                          <tr key={index}>
                            <td>
                              <div className="color-wrap"></div>
                            </td>
                            <td className="al-r"></td>
                            <td className="al-r"></td>
                            <td className="al-r"></td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                </div>
                {basicSetting && basicSetting.roofSizeSet === '3' && (
                  <div className="outline-form mt15">
                    <span>{getMessage('modal.module.basic.setting.module.placement.area')}</span>
                    <div className="input-grid mr10" style={{ width: '60px' }}>
                      <input
                        type="text"
                        className="input-origin block"
                        value={inputInstallHeight}
                        onChange={(e) => setInputInstallHeight(e.target.value)}
                      />
                    </div>
                    <span className="thin">m</span>
                  </div>
                )}
              </div>

              {basicSetting && basicSetting.roofSizeSet !== '3' && (
                <div className="compas-table-box">
                  <div className="compas-grid-table">
                    <div className="outline-form">
                      <span>{getMessage('modal.module.basic.setting.module.surface.type')}</span>
                      <div className="grid-select">
                        {roughnessCodes.length > 0 && managementState && (
                          <QSelectBox
                            options={roughnessCodes}
                            value={inputRoughness}
                            targetKey={'clCode'}
                            sourceKey={'clCode'}
                            showKey={'clCodeNm'}
                            onChange={(e) => {
                              console.log('🚀 ~ handleChangeModule ~ inputRoughness:', e)
                              setInputRoughness(e)
                            }}
                          />
                        )}
                      </div>
                    </div>
                    <div className="outline-form">
                      <span>{getMessage('modal.module.basic.setting.module.fitting.height')}</span>
                      <div className="input-grid mr10">
                        <input
                          type="text"
                          className="input-origin block"
                          value={inputInstallHeight}
                          onChange={(e) => setInputInstallHeight(e.target.value)}
                        />
                      </div>
                      <span className="thin">m</span>
                    </div>
                    <div className="outline-form">
                      <span>{getMessage('modal.module.basic.setting.module.standard.wind.speed')}</span>
                      <div className="grid-select">
                        {windSpeedCodes.length > 0 && managementState && (
                          <QSelectBox
                            title={''}
                            options={windSpeedCodes}
                            value={inputStandardWindSpeed}
                            targetKey={'clCode'}
                            sourceKey={'clCode'}
                            showKey={'clCodeNm'}
                            onChange={(e) => {
                              console.log('🚀 ~ handleChangeModule ~ inputStandardWindSpeed:', e)
                              setInputStandardWindSpeed(e)
                            }}
                          />
                        )}
                      </div>
                    </div>
                    <div className="outline-form">
                      <span>{getMessage('modal.module.basic.setting.module.standard.snowfall.amount')}</span>
                      <div className="input-grid 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>
    </>
  )
})
