import { POLYGON_TYPE } from '@/common/common'
import WithDraggable from '@/components/common/draggable/WithDraggable'
import { Orientation } from '@/components/floor-plan/modal/basic/step/Orientation'
import PitchPlacement from '@/components/floor-plan/modal/basic/step/pitch/PitchPlacement'
import Placement from '@/components/floor-plan/modal/basic/step/Placement'
import { useCanvasPopupStatusController } from '@/hooks/common/useCanvasPopupStatusController'
import { useMasterController } from '@/hooks/common/useMasterController'
import { useModuleBasicSetting } from '@/hooks/module/useModuleBasicSetting'
import { useModuleSelection } from '@/hooks/module/useModuleSelection'
import { useOrientation } from '@/hooks/module/useOrientation'
import { useMessage } from '@/hooks/useMessage'
import { usePopup } from '@/hooks/usePopup'
import {
  canvasState,
  checkedModuleState,
  currentCanvasPlanState,
  isManualModuleLayoutSetupState,
  isManualModuleSetupState,
  toggleManualSetupModeState,
} from '@/store/canvasAtom'
import { loginUserStore } from '@/store/commonAtom'
import { roofsState } from '@/store/roofAtom'
import { moduleSelectionDataState } from '@/store/selectedModuleOptions'
import { addedRoofsState, basicSettingState } from '@/store/settingAtom'
import { isObjectNotEmpty } from '@/util/common-utils'
import { useEffect, useRef, useState } from 'react'
import { useRecoilState, useRecoilValue } from 'recoil'
import Swal from 'sweetalert2'
import Trestle from './step/Trestle'

export default function BasicSetting({ id, pos = { x: 50, y: 230 } }) {
  const { getMessage } = useMessage()
  const { closePopup } = usePopup()
  const [tabNum, setTabNum] = useState(1)
  const orientationRef = useRef(null)
  const [isManualModuleSetup, setIsManualModuleSetup] = useRecoilState(isManualModuleSetupState)
  const [isManualModuleLayoutSetup, setIsManualModuleLayoutSetup] = useRecoilState(isManualModuleLayoutSetupState)
  const trestleRef = useRef(null)
  const [moduleSelectionData, setModuleSelectionData] = useRecoilState(moduleSelectionDataState)
  const [addedRoofs, setAddedRoofs] = useRecoilState(addedRoofsState)
  const loginUserState = useRecoilValue(loginUserStore)
  const currentCanvasPlan = useRecoilValue(currentCanvasPlanState)
  const canvas = useRecoilValue(canvasState)
  const [basicSetting, setBasicSettings] = useRecoilState(basicSettingState)
  const [isClosePopup, setIsClosePopup] = useState({ close: false, id: 0 })
  const [checkedModules, setCheckedModules] = useRecoilState(checkedModuleState)
  const [roofs, setRoofs] = useState(addedRoofs)
  const [manualSetupMode, setManualSetupMode] = useRecoilState(toggleManualSetupModeState)
  const [layoutSetup, setLayoutSetup] = useState([{}])
  const {
    selectedModules,
    roughnessCodes,
    windSpeedCodes,
    managementState,
    setManagementState,
    moduleList,
    setSelectedModules,
    selectedSurfaceType,
    setSelectedSurfaceType,
    installHeight,
    setInstallHeight,
    standardWindSpeed,
    setStandardWindSpeed,
    verticalSnowCover,
    setVerticalSnowCover,
    handleChangeModule,
    handleChangeSurfaceType,
    handleChangeWindSpeed,
    handleChangeInstallHeight,
    handleChangeVerticalSnowCover,
  } = useModuleSelection({ addedRoofs })
  const { nextStep, compasDeg, setCompasDeg } = useOrientation()
  const { trigger: orientationTrigger } = useCanvasPopupStatusController(1)
  const { trigger: trestleTrigger } = useCanvasPopupStatusController(2)
  const { trigger: placementTrigger } = useCanvasPopupStatusController(3)
  const [roofsStore, setRoofsStore] = useRecoilState(roofsState)

  // const { initEvent } = useContext(EventContext)
  const { manualModuleSetup, autoModuleSetup, manualFlatroofModuleSetup, autoFlatroofModuleSetup, manualModuleLayoutSetup, restoreModuleInstArea } =
    useModuleBasicSetting(tabNum)
  const { updateObjectDate } = useMasterController()

  useEffect(() => {
    const moduleTabNum = basicSetting.roofSizeSet != 3 ? 3 : 2

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

    if (hasModules) {
      orientationRef.current.handleNextStep()
      setTabNum(moduleTabNum)
    }
  }, [])

  useEffect(() => {
    if (roofsStore && addedRoofs) {
      setRoofs(
        addedRoofs.map((roof, index) => {
          return {
            ...roof,
            ...roofsStore[index]?.addRoof,
            construction: roofsStore[index]?.construction,
            trestle: roofsStore[index]?.trestle,
            trestleDetail: roofsStore[index]?.trestleDetail,
          }
        }),
      )

      setModuleSelectionData({
        ...moduleSelectionData,
        roofConstructions: roofsStore.map((roof) => {
          return {
            roofIndex: roof.roofIndex,
            addRoof: roof.addRoof,
            construction: roof.construction,
            trestle: roof.trestle,
            trestleDetail: roof.trestleDetail,
          }
        }),
      })
    }
  }, [roofsStore, addedRoofs])

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

  useEffect(() => {
    setIsManualModuleSetup(false)
  }, [checkedModules])

  useEffect(() => {
    if (basicSetting.roofSizeSet !== '3') {
      if (manualSetupMode.indexOf('manualSetup') > -1) {
        manualModuleSetup()
      } else if (manualSetupMode.indexOf('manualLayoutSetup') > -1) {
        manualModuleLayoutSetup(layoutSetup)
      } else if (manualSetupMode.indexOf('off') > -1) {
        manualModuleSetup()
        manualModuleLayoutSetup(layoutSetup)
      }
    } else {
      manualFlatroofModuleSetup(placementFlatRef)
    }

    if (isClosePopup.close) {
      closePopup(isClosePopup.id)
    }
  }, [manualSetupMode, isClosePopup])

  useEffect(() => {
    if (isManualModuleLayoutSetup) {
      manualModuleLayoutSetup(layoutSetup)
    }
  }, [layoutSetup])

  useEffect(() => {
    setIsManualModuleSetup(false)
    setIsManualModuleLayoutSetup(false)
    setManualSetupMode(`off`)
  }, [checkedModules])

  const handleBtnNextStep = () => {
    if (tabNum === 1) {
      orientationRef.current.handleNextStep()
      setAddedRoofs(roofs)
      // setTabNum(tabNum + 1)
      return
    } else if (tabNum === 2) {
      if (basicSetting.roofSizeSet !== '3') {
        // if (addedRoofs.length !== moduleSelectionData.roofConstructions.length) {
        //   Swal.fire({
        //     title: getMessage('construction.length.difference'),
        //     icon: 'warning',
        //   })
        //   return
        // }
        trestleRef.current.isComplete().then((res) => {
          if (!res) return
        })
        //물건정보 갱신일 수정
      } else {
        if (!isObjectNotEmpty(moduleSelectionData.module)) {
          Swal.fire({
            title: getMessage('module.not.found'),
            icon: 'warning',
          })
          return
        }

        setTabNum(tabNum + 1)
      }
    }
  }

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

  const handleManualModuleSetup = () => {
    setManualSetupMode(`manualSetup_${!isManualModuleSetup}`)
    setIsManualModuleSetup(!isManualModuleSetup)
  }

  const handleManualModuleLayoutSetup = () => {
    setManualSetupMode(`manualLayoutSetup_${!isManualModuleLayoutSetup}`)
    setIsManualModuleLayoutSetup(!isManualModuleLayoutSetup)
  }

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

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

  const orientationProps = {
    roofs,
    setRoofs,
    tabNum,
    setTabNum,
    compasDeg, // 방위각
    setCompasDeg,
    selectedModules,
    moduleSelectionData,
    setModuleSelectionData,
    roughnessCodes, // 면조도 목록
    windSpeedCodes, // 기준풍속 목록
    managementState,
    setManagementState,
    moduleList, // 모듈 리스트
    setSelectedModules,
    selectedSurfaceType,
    setSelectedSurfaceType,
    installHeight, // 설치높이
    setInstallHeight,
    standardWindSpeed, // 기준풍속
    setStandardWindSpeed,
    verticalSnowCover, // 적설량
    setVerticalSnowCover,
    currentCanvasPlan,
    loginUserState,
    handleChangeModule,
    handleChangeSurfaceType,
    handleChangeWindSpeed,
    handleChangeInstallHeight,
    handleChangeVerticalSnowCover,
    orientationTrigger,
    nextStep,
    updateObjectDataApi,
  }
  const trestleProps = {
    roofs,
    setRoofs,
    setRoofsStore,
    tabNum,
    setTabNum,
    moduleSelectionData,
    setModuleSelectionData,
    trestleTrigger,
  }
  const placementProps = {}

  return (
    <WithDraggable isShow={true} pos={pos} className={basicSetting.roofSizeSet && basicSetting.roofSizeSet != '3' ? 'll' : 'lx-2'}>
      <WithDraggable.Header title={getMessage('plan.menu.module.circuit.setting.default')} onClose={() => handleClosePopup(id)} />
      <WithDraggable.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>
          {basicSetting.roofSizeSet && basicSetting.roofSizeSet != '3' && (
            <>
              <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>
            </>
          )}
          {basicSetting.roofSizeSet && basicSetting.roofSizeSet == '3' && (
            <>
              <div className={`module-tab-bx ${tabNum === 2 ? 'act' : ''}`}>{getMessage('modal.module.basic.setting.module.placement')}</div>
            </>
          )}
        </div>
        {tabNum === 1 && <Orientation ref={orientationRef} {...orientationProps} />}
        {/*배치면 초기설정 - 입력방법: 복시도 입력 || 실측값 입력*/}
        {basicSetting.roofSizeSet && basicSetting.roofSizeSet != '3' && tabNum === 2 && <Trestle ref={trestleRef} {...trestleProps} />}
        {basicSetting.roofSizeSet && basicSetting.roofSizeSet != '3' && tabNum === 3 && (
          <Placement setTabNum={setTabNum} layoutSetup={layoutSetup} setLayoutSetup={setLayoutSetup} />
        )}
        {/*배치면 초기설정 - 입력방법: 육지붕*/}
        {/* {basicSetting.roofSizeSet && basicSetting.roofSizeSet == '3' && tabNum === 3 && <PitchModule setTabNum={setTabNum} />} */}
        {basicSetting.roofSizeSet && basicSetting.roofSizeSet == '3' && tabNum === 2 && (
          <PitchPlacement setTabNum={setTabNum} ref={placementFlatRef} />
        )}

        <div className="grid-btn-wrap">
          {/* {tabNum === 1 && <button className="btn-frame modal mr5">{getMessage('modal.common.save')}</button>} */}
          {basicSetting.roofSizeSet && basicSetting.roofSizeSet != '3' && (
            <>
              {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" onClick={handleBtnNextStep}>
                  Next
                </button>
              )}
              {tabNum === 3 && (
                <>
                  <button className={`btn-frame modal mr5 ${isManualModuleLayoutSetup ? 'act' : ''}`} onClick={handleManualModuleLayoutSetup}>
                    {getMessage('modal.module.basic.setting.row.batch')}
                  </button>
                  <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()}>
                    {getMessage('modal.module.basic.setting.auto.placement')}
                  </button>
                </>
              )}
            </>
          )}
          {basicSetting.roofSizeSet && basicSetting.roofSizeSet == '3' && (
            <>
              {tabNum === 1 && (
                <button className="btn-frame modal" onClick={handleBtnNextStep}>
                  Next
                </button>
              )}
              {tabNum === 2 && (
                <>
                  <button className="btn-frame modal mr5" onClick={() => setTabNum(tabNum - 1)}>
                    {getMessage('modal.module.basic.setting.prev')}
                  </button>
                  <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>
      </WithDraggable.Body>
    </WithDraggable>
  )
}
