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, 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'

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 [pcsCheck, setPcsCheck] = useRecoilState(pcsCheckState)

  const [tabNum, setTabNum] = useState(1)
  const [allocationType, setAllocationType] = useState(ALLOCATION_TYPE.AUTO)
  const [circuitAllocationType, setCircuitAllocationType] = useState(1)

  const powerConditionalSelectProps = {
    tabNum,
    setTabNum,
    makers,
    setMakers,
    selectedMaker,
    setSelectedMaker,
    series,
    setSeries,
    models,
    setModels,
  }

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

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

    if (selectedModels.length === 0) {
      moduleStdQty = models.reduce((acc, model) => {
        return acc + parseInt(model.moduleStdQty)
      }, 0)

      moduleMaxQty = models.reduce((acc, model) => {
        return acc + parseInt(model.moduleMaxQty)
      }, 0)
    } 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 = () => {
    console.log('🚀 ~ onPassivityAllocation ~ selectedModels:', models)

    if (models.filter((m) => m.selected).length === 0) {
      swalFire({
        title: '파워 컨디셔너를 추가해 주세요.',
        type: 'alert',
      })
      return
    } else if (pcsCheck.max) {
      const selectedModels = models.filter((m) => m.selected)
      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>
  )
}
