import { useMessage } from '@/hooks/useMessage'
import WithDraggable from '@/components/common/draggable/WithDraggable'
import { useContext, useEffect, useRef, useState } from 'react'
import Module from '@/components/floor-plan/modal/basic/step/Module'
import PitchModule from '@/components/floor-plan/modal/basic/step/pitch/PitchModule'
import PitchPlacement from '@/components/floor-plan/modal/basic/step/pitch/PitchPlacement'
import Placement from '@/components/floor-plan/modal/basic/step/Placement'
import { useRecoilValue, useRecoilState } from 'recoil'
import { canvasSettingState, canvasState, isManualModuleSetupState } from '@/store/canvasAtom'
import { usePopup } from '@/hooks/usePopup'
import { Orientation } from '@/components/floor-plan/modal/basic/step/Orientation'
import { useModuleBasicSetting } from '@/hooks/module/useModuleBasicSetting'
import { useEvent } from '@/hooks/useEvent'
import { moduleSelectionDataState } from '@/store/selectedModuleOptions'
import { addedRoofsState, corridorDimensionSelector } from '@/store/settingAtom'
import { isObjectNotEmpty } from '@/util/common-utils'
import Swal from 'sweetalert2'
import { useCanvasPopupStatusController } from '@/hooks/common/useCanvasPopupStatusController'
import { useMasterController } from '@/hooks/common/useMasterController'
import { loginUserStore } from '@/store/commonAtom'
import { currentCanvasPlanState } from '@/store/canvasAtom'
import { POLYGON_TYPE } from '@/common/common'

export default function BasicSetting({ id, pos = { x: 50, y: 230 } }) {
  const { getMessage } = useMessage()
  const { closePopup } = usePopup()
  const [tabNum, setTabNum] = useState(1)
  const canvasSetting = useRecoilValue(canvasSettingState)
  const orientationRef = useRef(null)
  const { initEvent } = useEvent()
  const [isManualModuleSetup, setIsManualModuleSetup] = useRecoilState(isManualModuleSetupState)
  const moduleSelectionData = useRecoilValue(moduleSelectionDataState)
  const addedRoofs = useRecoilValue(addedRoofsState)
  const loginUserState = useRecoilValue(loginUserStore)
  const currentCanvasPlan = useRecoilValue(currentCanvasPlanState)
  const canvas = useRecoilValue(canvasState)

  const [isClosePopup, setIsClosePopup] = useState({ close: false, id: 0 })

  // const { initEvent } = useContext(EventContext)
  const { manualModuleSetup, autoModuleSetup, manualFlatroofModuleSetup, autoFlatroofModuleSetup } = useModuleBasicSetting(tabNum)
  const { updateObjectDate } = useMasterController()
  const handleBtnNextStep = () => {
    if (tabNum === 1) {
      orientationRef.current.handleNextStep()
    } else if (tabNum === 2) {
      if (canvasSetting.roofSizeSet !== '3') {
        if (!isObjectNotEmpty(moduleSelectionData.module)) {
          Swal.fire({
            title: getMessage('module.not.found'),
            icon: 'warning',
          })
          return
        }

        if (addedRoofs.length !== moduleSelectionData.roofConstructions.length) {
          Swal.fire({
            title: getMessage('construction.length.difference'),
            icon: 'warning',
          })
          return
        }
        //물건정보 갱신일 수정
        updateObjectDataApi({
          objectNo: currentCanvasPlan.objectNo, //오브젝트_no
          standardWindSpeedId: moduleSelectionData.common.stdWindSpeed, //기준풍속코드
          verticalSnowCover: moduleSelectionData.common.stdSnowLd, //적설량
          surfaceType: moduleSelectionData.common.illuminationTpNm, //면조도구분
          installHeight: moduleSelectionData.common.instHt, //설치높이
          userId: loginUserState.userId, //작성자아아디
        })
      } else {
        if (!isObjectNotEmpty(moduleSelectionData.flatModule)) {
          Swal.fire({
            title: getMessage('module.not.found'),
            icon: 'warning',
          })
          return
        }
      }
    }

    setTabNum(tabNum + 1)
  }

  const placementRef = {
    isChidori: useRef('false'),
    setupLocation: useRef('eaves'),
    isMaxSetup: useRef('false'),
  }

  const placementFlatRef = {
    setupLocation: useRef('south'),
  }

  const handleManualModuleSetup = () => {
    setIsManualModuleSetup(!isManualModuleSetup)
  }

  const updateObjectDataApi = async (params) => {
    const res = await updateObjectDate(params)
  }

  useEffect(() => {
    let hasModules = canvas
      .getObjects()
      .filter((obj) => obj.name === POLYGON_TYPE.MODULE_SETUP_SURFACE)
      .some((obj) => obj.modules?.length > 0)

    if (hasModules) {
      setTabNum(3)
    }
  }, [])

  //팝업 닫기 버튼 이벤트
  const handleClosePopup = (id) => {
    if (tabNum == 3) {
      if (isManualModuleSetup) {
        setIsManualModuleSetup(false)
      }
    }
    setIsClosePopup({ close: true, id: id })
  }

  useEffect(() => {
    if (canvasSetting.roofSizeSet !== '3') {
      manualModuleSetup(placementRef)
    } else {
      manualFlatroofModuleSetup(placementFlatRef)
    }
    if (isClosePopup.close) {
      closePopup(isClosePopup.id)
    }
  }, [isManualModuleSetup, isClosePopup])

  return (
    <WithDraggable isShow={true} pos={pos}>
      <div className={`modal-pop-wrap lx-2`}>
        <div className="modal-head modal-handle">
          <h1 className="title">{getMessage('plan.menu.module.circuit.setting.default')}</h1>
          <button className="modal-close" onClick={() => handleClosePopup(id)}>
            닫기
          </button>
        </div>
        <div className="modal-body">
          <div className="roof-module-tab">
            <div className={`module-tab-bx act`}>{getMessage('modal.module.basic.setting.orientation.setting')}</div>
            <span className={`tab-arr ${tabNum !== 1 ? 'act' : ''}`}></span>
            <div className={`module-tab-bx ${tabNum !== 1 ? 'act' : ''}`}>{getMessage('modal.module.basic.setting.module.setting')}</div>
            <span className={`tab-arr ${tabNum === 3 ? 'act' : ''}`}></span>
            <div className={`module-tab-bx ${tabNum === 3 ? 'act' : ''}`}>{getMessage('modal.module.basic.setting.module.placement')}</div>
          </div>
          {tabNum === 1 && <Orientation ref={orientationRef} tabNum={tabNum} setTabNum={setTabNum} />}
          {/*배치면 초기설정 - 입력방법: 복시도 입력 || 실측값 입력*/}
          {canvasSetting.roofSizeSet && canvasSetting.roofSizeSet != '3' && tabNum === 2 && <Module setTabNum={setTabNum} />}
          {canvasSetting.roofSizeSet && canvasSetting.roofSizeSet != '3' && tabNum === 3 && <Placement setTabNum={setTabNum} ref={placementRef} />}

          {/*배치면 초기설정 - 입력방법: 육지붕*/}
          {canvasSetting.roofSizeSet && canvasSetting.roofSizeSet == '3' && tabNum === 2 && <PitchModule setTabNum={setTabNum} />}
          {canvasSetting.roofSizeSet && canvasSetting.roofSizeSet == '3' && tabNum === 3 && (
            <PitchPlacement setTabNum={setTabNum} ref={placementFlatRef} />
          )}

          <div className="grid-btn-wrap">
            {tabNum !== 1 && (
              <button className="btn-frame modal mr5" onClick={() => setTabNum(tabNum - 1)}>
                {getMessage('modal.module.basic.setting.prev')}
              </button>
            )}
            {/*{tabNum !== 3 && <button className="btn-frame modal act mr5">{getMessage('modal.common.save')}</button>}*/}
            {tabNum !== 3 && (
              <button className="btn-frame modal" onClick={handleBtnNextStep}>
                Next
              </button>
            )}

            {tabNum === 3 && (
              <>
                {canvasSetting.roofSizeSet && canvasSetting.roofSizeSet != 3 && (
                  <>
                    <button className={`btn-frame modal mr5 ${isManualModuleSetup ? 'act' : ''}`} onClick={handleManualModuleSetup}>
                      {getMessage('modal.module.basic.setting.passivity.placement')}
                    </button>
                    <button className="btn-frame modal act" onClick={() => autoModuleSetup(placementRef)}>
                      {getMessage('modal.module.basic.setting.auto.placement')}
                    </button>
                  </>
                )}
                {canvasSetting.roofSizeSet && canvasSetting.roofSizeSet === 3 && (
                  <>
                    <button className={`btn-frame modal mr5 ${isManualModuleSetup ? 'act' : ''}`} onClick={handleManualModuleSetup}>
                      {getMessage('modal.module.basic.setting.passivity.placement')}
                    </button>
                    <button className="btn-frame modal act" onClick={() => autoFlatroofModuleSetup(placementFlatRef)}>
                      {getMessage('modal.module.basic.setting.auto.placement')}
                    </button>
                  </>
                )}
              </>
            )}
          </div>
        </div>
        <div className="modal-foot modal-handle"></div>
      </div>
    </WithDraggable>
  )
}
