import WithDraggable from '@/components/common/draggable/WithDraggable'
import { useState, useEffect, useContext } from 'react'
import PowerConditionalSelect from '@/components/floor-plan/modal/circuitTrestle/step/PowerConditionalSelect'
import CircuitAllocation from '@/components/floor-plan/modal/circuitTrestle/step/CircuitAllocation'
import StepUp from '@/components/floor-plan/modal/circuitTrestle/step/StepUp'
import { useMessage } from '@/hooks/useMessage'
import { usePopup } from '@/hooks/usePopup'
import PassivityCircuitAllocation from './step/type/PassivityCircuitAllocation'
import { useMasterController } from '@/hooks/common/useMasterController'
import { correntObjectNoState } from '@/store/settingAtom'
import { useRecoilValue } from 'recoil'
import { GlobalDataContext } from '@/app/GlobalDataProvider'
import { useRecoilState } from 'recoil'
import { makersState, modelsState, modelState, pcsCheckState, selectedMakerState, selectedModelsState, seriesState } from '@/store/circuitTrestleAtom'
import { POLYGON_TYPE } from '@/common/common'
import { useSwal } from '@/hooks/useSwal'
import { canvasState } from '@/store/canvasAtom'

import { useTrestle } from '@/hooks/module/useTrestle'
import { selectedModuleState } from '@/store/selectedModuleOptions'

const ALLOCATION_TYPE = {
  AUTO: 'auto',
  PASSIVITY: 'passivity',
}
export default function CircuitTrestleSetting({ id }) {
  const { getMessage } = useMessage()
  const { closePopup } = usePopup()
  const { apply } = useTrestle()
  const { swalFire } = useSwal()
  const canvas = useRecoilValue(canvasState)

  const [makers, setMakers] = useRecoilState(makersState)
  const [selectedMaker, setSelectedMaker] = useRecoilState(selectedMakerState)
  const [series, setSeries] = useRecoilState(seriesState)
  const [models, setModels] = useRecoilState(modelsState)
  const [selectedModels, setSelectedModels] = useRecoilState(selectedModelsState)
  const [pcsCheck, setPcsCheck] = useRecoilState(pcsCheckState)

  const [tabNum, setTabNum] = useState(1)
  const [allocationType, setAllocationType] = useState(ALLOCATION_TYPE.AUTO)
  const [circuitAllocationType, setCircuitAllocationType] = useState(1)
  const { managementState, setManagementState, managementStateLoaded } = useContext(GlobalDataContext)
  const selectedModules = useRecoilValue(selectedModuleState)
  const { getPcsAutoRecommendList } = useMasterController()
  const powerConditionalSelectProps = {
    tabNum,
    setTabNum,
    makers,
    setMakers,
    selectedMaker,
    setSelectedMaker,
    series,
    setSeries,
    models,
    setModels,
    selectedModels,
    setSelectedModels,
    managementState,
  }

  const passivityProps = {
    tabNum,
    setTabNum,
    pcsCheck,
    selectedModels,
    setSelectedModels,
  }
  const stepUpProps = {
    tabNum,
    setTabNum,
    models,
    setModels,
    circuitAllocationType,
    setCircuitAllocationType,
  }

  useEffect(() => {
    if (!managementState) {
      setManagementState(managementStateLoaded)
    }
  }, [])

  const onAutoRecommend = () => {
    if (series.filter((s) => s.selected).length === 0) {
      swalFire({
        title: '시리즈를 선택해 주세요.',
        type: 'alert',
      })
      return
    }
    const roofSurfaceList = canvas
      .getObjects()
      .filter((obj) => obj.name === POLYGON_TYPE.MODULE_SETUP_SURFACE)
      .map((obj) => {
        return {
          roofSurfaceId: obj.id,
          roofSurface: canvas
            .getObjects()
            .filter((o) => o.id === obj.parentId)[0]
            .directionText.replace(/[0-9]/g, ''),
          roofSurfaceIncl: canvas.getObjects().filter((o) => o.id === obj.parentId)[0].roofMaterial.pitch,
          moduleList: obj.modules.map((module) => {
            return {
              itemId: module.moduleInfo.itemId,
            }
          }),
        }
      })

    const params = {
      maxConnYn: pcsCheck.max ? 'Y' : 'N',
      smpCirYn: pcsCheck.division ? 'Y' : 'N',
      coldZoneYn: managementState?.coldRegionFlg === '1' ? 'Y' : 'N',
      useModuleItemList: selectedModules.itemList.map((m) => {
        return {
          itemId: m.itemId,
          mixMatlNo: m.mixMatlNo,
        }
      }),
      roofSurfaceList: roofSurfaceList,
      pcsItemList: models.map((model) => {
        return {
          itemId: model.itemId,
          pcsMkrCd: model.pcsMkrCd,
          pcsSerCd: model.pcsSerCd,
        }
      }),
    }
    getPcsAutoRecommendList(params).then((res) => {
      if (res.data?.pcsItemList) {
        setModels(res.data.pcsItemList)
        setTabNum(2)
      } else {
        swalFire({
          title: '파워컨디셔너를 추가해 주세요.',
          type: 'alert',
        })
      }
    })
  }

  const onAutoAllocation = () => {
    let moduleStdQty = 0
    let moduleMaxQty = 0
    const selectedModels = models.filter((m) => m.selected)

    if (selectedModels.length === 0) {
      onAutoRecommend()
    } else {
      moduleStdQty = selectedModels.reduce((acc, model) => {
        return acc + parseInt(model.moduleStdQty)
      }, 0)
      moduleMaxQty = selectedModels.reduce((acc, model) => {
        return acc + parseInt(model.moduleMaxQty)
      }, 0)
    }
    const target = pcsCheck.max ? moduleMaxQty : moduleStdQty
    const placementModules = canvas.getObjects().filter((obj) => obj.name === POLYGON_TYPE.MODULE)

    if (placementModules.length > target) {
      swalFire({
        title: '배치가능 매수를 초과합니다. 파워컨디셔너를 다시 선택해 주세요.',
        type: 'alert',
      })
      return
    }

    // setAllocationType(ALLOCATION_TYPE.AUTO)
    setTabNum(2)
  }

  const onPassivityAllocation = () => {
    if (selectedModels.length === 0) {
      swalFire({
        title: '파워 컨디셔너를 추가해 주세요.',
        type: 'alert',
      })
      return
    } else if (pcsCheck.max) {
      const moduleStdQty = selectedModels.reduce((acc, model) => {
        return acc + parseInt(model.moduleStdQty)
      }, 0)
      const moduleMaxQty = selectedModels.reduce((acc, model) => {
        return acc + parseInt(model.moduleMaxQty)
      }, 0)

      const target = pcsCheck.max ? moduleMaxQty : moduleStdQty
      const placementModules = canvas.getObjects().filter((obj) => obj.name === POLYGON_TYPE.MODULE)

      if (placementModules.length > target) {
        swalFire({
          title: '배치가능 매수를 초과합니다. 파워컨디셔너를 다시 선택해 주세요.',
          type: 'alert',
        })
        return
      }
    }

    setAllocationType(ALLOCATION_TYPE.PASSIVITY)
  }

  return (
    <WithDraggable isShow={true} pos={{ x: 50, y: 230 }}>
      <div className={`modal-pop-wrap l-2`}>
        <div className="modal-head modal-handle">
          <h1 className="title">{getMessage('modal.circuit.trestle.setting')} </h1>
          <button className="modal-close" onClick={() => closePopup(id)}>
            닫기
          </button>
        </div>
        <div className="modal-body">
          <div className="roof-module-tab">
            <div className={`module-tab-bx act`}>{getMessage('modal.circuit.trestle.setting.power.conditional.select')}</div>
            <span className={`tab-arr ${tabNum === 2 ? 'act' : ''}`}></span>
            <div className={`module-tab-bx ${tabNum === 2 ? 'act' : ''}`}>
              {getMessage('modal.circuit.trestle.setting.circuit.allocation')}({getMessage('modal.circuit.trestle.setting.step.up.allocation')})
            </div>
          </div>
          {tabNum === 1 && allocationType === ALLOCATION_TYPE.AUTO && <PowerConditionalSelect {...powerConditionalSelectProps} />}
          {tabNum === 1 && allocationType === ALLOCATION_TYPE.PASSIVITY && <PassivityCircuitAllocation {...passivityProps} />}
          {tabNum === 2 && <StepUp {...stepUpProps} />}
          {tabNum === 1 && allocationType === ALLOCATION_TYPE.AUTO && (
            <div className="grid-btn-wrap">
              <button className="btn-frame modal mr5" onClick={() => onAutoAllocation()}>
                {getMessage('modal.circuit.trestle.setting.circuit.allocation.auto')}
              </button>
              <button className="btn-frame modal act" onClick={() => onPassivityAllocation()}>
                {getMessage('modal.circuit.trestle.setting.circuit.allocation.passivity')}
              </button>
            </div>
          )}
          {tabNum === 1 && allocationType === ALLOCATION_TYPE.PASSIVITY && (
            <div className="grid-btn-wrap">
              <button className="btn-frame modal mr5" onClick={() => setAllocationType(ALLOCATION_TYPE.AUTO)}>
                {getMessage('modal.common.prev')}
              </button>
              <button className="btn-frame modal act" onClick={() => setTabNum(2)}>
                {getMessage('modal.circuit.trestle.setting.circuit.allocation')}({getMessage('modal.circuit.trestle.setting.step.up.allocation')})
              </button>
            </div>
          )}
          {tabNum === 2 && (
            <div className="grid-btn-wrap">
              <button className="btn-frame modal mr5" onClick={() => setTabNum(1)}>
                {getMessage('modal.common.prev')}
              </button>
              <button className="btn-frame modal act" onClick={() => apply()}>
                {getMessage('modal.common.save')}({getMessage('modal.circuit.trestle.setting.circuit.allocation')})
              </button>
            </div>
          )}
        </div>
        <div className="modal-foot modal-handle"></div>
      </div>
    </WithDraggable>
  )
}
