import { GlobalDataContext } from '@/app/GlobalDataProvider'
import QSelectBox from '@/components/common/select/QSelectBox'
import { useCanvasPopupStatusController } from '@/hooks/common/useCanvasPopupStatusController'
import { useMasterController } from '@/hooks/common/useMasterController'
import { useMessage } from '@/hooks/useMessage'
import { useSwal } from '@/hooks/useSwal'
import { pcsCheckState } from '@/store/circuitTrestleAtom'
import { sessionStore } from '@/store/commonAtom'
import { globalLocaleStore } from '@/store/localeAtom'
import { moduleSelectionDataState, selectedModuleState } from '@/store/selectedModuleOptions'
import { isNullOrUndefined } from '@/util/common-utils'
import { useContext, useEffect, useState } from 'react'
import { useRecoilState } from 'recoil'
import { useRecoilValue } from 'recoil'
import { v4 as uuidv4 } from 'uuid'

export const PCS_MKR_MULTI_TYPE = {
  MULTI: 'MULTI',
  SINGLE_P: 'SINGLE-P',
  SINGLE_N: 'SINGLE-N',
}

export default function PowerConditionalSelect(props) {
  let {
    tabNum,
    setTabNum,
    makers,
    setMakers,
    selectedMaker,
    setSelectedMaker,
    series,
    setSeries,
    models,
    setModels,
    selectedModels,
    setSelectedModels,
    managementState,
    getUseModuleItemList,
  } = props
  const [pcsCheck, setPcsCheck] = useRecoilState(pcsCheckState)

  const sessionState = useRecoilValue(sessionStore)
  const { getMessage } = useMessage()
  const [selectedRow, setSelectedRow] = useState(null)
  const globalLocale = useRecoilValue(globalLocaleStore)
  const { getPcsMakerList, getPcsModelList } = useMasterController()
  const selectedModules = useRecoilValue(selectedModuleState)
  const { swalFire } = useSwal()
  // const { trigger: moduleSelectedDataTrigger } = useCanvasPopupStatusController(2)
  const [moduleSelectionData, setModuleSelectionData] = useRecoilState(moduleSelectionDataState)
  const modelHeader = [
    { name: getMessage('modal.circuit.trestle.setting.circuit.allocation.passivity.series'), width: '15%', prop: 'pcsSerNm', type: 'color-box' },
    { name: getMessage('modal.circuit.trestle.setting.circuit.allocation.passivity.name'), width: '15%', prop: 'goodsNo', type: 'color-box' },
    {
      name: `${getMessage('modal.circuit.trestle.setting.power.conditional.select.rated.output')} (kW)`,
      width: '10%',
      prop: 'ratedCapa',
    },
    {
      name: `${getMessage('modal.circuit.trestle.setting.power.conditional.select.circuit.amount')}`,
      width: '10%',
      prop: 'paralMax',
    },
    {
      name: `${getMessage('modal.circuit.trestle.setting.power.conditional.select.max.connection')}`,
      width: '10%',
      prop: 'moduleStdQty',
    },
    {
      name: `${getMessage('modal.circuit.trestle.setting.power.conditional.select.max.overload')}`,
      width: '10%',
      prop: 'moduleMaxQty',
    },
  ]

  useEffect(() => {
    getPcsMakerList().then((res) => {
      setMakers(res.data)
    })
  }, [])

  const onCheckSeries = (data) => {
    let copySeries = []
    if (data.pcsMkrMultiType === PCS_MKR_MULTI_TYPE.MULTI) {
      copySeries = series.map((s) => {
        return {
          ...s,
          selected: s.pcsSerCd === data.pcsSerCd ? !s.selected : s.selected,
        }
      })
    } else if (data.pcsMkrMultiType === PCS_MKR_MULTI_TYPE.SINGLE_P) {
      if (series.filter((s) => s.selected).length === 0 && data.pcsSerParallelYn === 'Y') {
        swalFire({
          title: getMessage('modal.module.pcs.error1'),
          icon: 'warning',
        })

        return
      }
      copySeries = series.map((s) => {
        return {
          ...s,
          selected: s.pcsSerCd === data.pcsSerCd ? !s.selected : data.pcsSerParallelYn === 'Y' ? s.selected : false,
        }
      })
    } else {
      copySeries = series.map((s) => {
        return {
          ...s,
          selected: s.pcsSerCd === data.pcsSerCd ? !s.selected : false,
        }
      })
      setSelectedModels([])
    }
    setSeries(copySeries)
    handleSetmodels(copySeries.filter((s) => s.selected))
  }

  const handleSetmodels = (selectedSeries) => {
    if (selectedSeries.length === 0) {
      setModels([])
      setSelectedModels([])
      return
    }
    const pcsMkrCd = selectedSeries[0]?.pcsMkrCd
    const pcsSerList = selectedSeries.map((series) => {
      return { pcsSerCd: series.pcsSerCd }
    })
    const moduleItemList = moduleSelectionData.module.itemList.map((item) => {
      return {
        itemId: item.itemId,
        mixMatlNo: item.mixMatlNo,
      }
    })
    getPcsModelList({ pcsMkrCd, pcsSerList, moduleItemList, storeId: sessionState.storeId }).then((res) => {
      if (res?.result.code === 200 && res?.data) {
        setModels(
          res.data.map((model) => {
            return {
              ...model,
              moduleStdQty: parseInt(model.moduleStdQty),
              moduleMaxQty: parseInt(model.moduleMaxQty),
              code: uuidv4(),
            }
          }),
        )
      } else {
        setModels([])
        setSelectedModels([])
      }
    })
  }

  const onAddSelectedModel = () => {
    if (selectedRow === null) return
    if (selectedModels.length === 3) {
      swalFire({
        title: getMessage('max.select', [3]),
        icon: 'warning',
      })

      return
    }

    if (selectedModels.find((m) => m.pcsSerParallelYn === 'Y') && selectedRow.pcsSerParallelYn === 'Y') {
      return
    }

    if (selectedRow.pcsSerParallelYn === 'Y' && selectedModels.length === 0 && selectedMaker.pcsMkrMultiType === PCS_MKR_MULTI_TYPE.SINGLE_P) {
      swalFire({
        title: getMessage('modal.module.pcs.error1'),
        icon: 'warning',
      })

      return
    }

    if (selectedMaker.pcsMkrMultiType === PCS_MKR_MULTI_TYPE.MULTI) {
      setSelectedModels([...selectedModels, { ...selectedRow, id: uuidv4() }])
    } else if (!selectedModels.find((m) => m.itemId === selectedRow.itemId && m.pcsSerCd === selectedRow.pcsSerCd)) {
      setSelectedModels([...selectedModels, { ...selectedRow, id: uuidv4() }])
    }
    setSelectedRow(null)
  }

  const onRemoveSelectedModel = (model) => {
    const tempModels = selectedModels.filter((m) => m.id !== model.id)
    if (tempModels.length === 1 && tempModels[0].pcsSerParallelYn === 'Y') {
      setSelectedModels([])
      return
    }
    setSelectedModels(selectedModels.filter((m) => m.id !== model.id))
  }

  const onChangeMaker = (option) => {
    if (option) {
      setModels([])
      setSelectedModels([])
      setSelectedMaker(option)
      const param = {
        pcsMkrCd: option.pcsMkrCd,
        mixMatlNo: moduleSelectionData.module.mixMatlNo,
        moduleMatlCds: moduleSelectionData.module.itemList.map((item) => item.itemId).join(','),
      }

      getPcsMakerList(param).then((res) => {
        setSeries(
          res.data.map((series) => {
            return { ...series, selected: false }
          }),
        )
      })
    }
  }

  return (
    <>
      <div className="outline-form mb15">
        <span className="mr10">
          {getMessage('common.type')} ({getMessage(managementState?.conType === '0' ? 'stuff.detail.conType0' : 'stuff.detail.conType1')})
        </span>
        <div className="grid-select mr10">
          <QSelectBox
            title={'PCS Maker'}
            options={makers}
            showKey={globalLocale === 'ko' ? 'pcsMkrNm' : 'pcsMkrNmJp'}
            sourceKey="pcsMkrCd"
            targetKey="pcsMkrCd"
            value={selectedMaker}
            onChange={(option) => onChangeMaker(option)}
          />
        </div>
        {managementState?.coldRegionFlg === '1' && (
          <span className="thin">{getMessage('modal.circuit.trestle.setting.power.conditional.select.cold.region')}</span>
        )}
      </div>
      <div className="module-table-box mb10">
        <div className="module-table-inner">
          <div className="circuit-check-inner overflow">
            {series?.map((series, index) => (
              <div className="d-check-box pop sel" key={`series-${index}`}>
                <input type="checkbox" id={`"ch0"${index}`} onChange={() => onCheckSeries(series)} checked={series.selected} />
                <label htmlFor={`"ch0"${index}`}>{globalLocale === 'ko' ? series.pcsSerNm : series.pcsSerNmJp}</label>
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="module-table-box mb15">
        <div className="module-table-inner">
          <div className="x-scroll-table mb10">
            <div className="roof-module-table">
              <table>
                <thead>
                  <tr>
                    {modelHeader.map((header) => (
                      <th key={header.prop} style={{ width: header.width }}>
                        {header.name}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {models?.map((model, index) => (
                    <tr key={index} onClick={() => setSelectedRow(model)} className={model === selectedRow ? 'on' : ''}>
                      {modelHeader.map((header, index) => (
                        <td key={index}>{model[header.prop]}</td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
          <div className="circuit-right-wrap mb10">
            <button className="btn-frame self mr5" onClick={() => onAddSelectedModel()}>
              {getMessage('modal.common.add')}
            </button>
          </div>
          <div className="circuit-data-form">
            {selectedModels?.map((model, index) => (
              <span className="normal-font" key={`model-${index}`}>
                {model.goodsNo} <button className="del" onClick={() => onRemoveSelectedModel(model)}></button>
              </span>
            ))}
          </div>
        </div>
      </div>
      <div className="slope-wrap">
        <div className="d-check-box pop mb15">
          <input type="checkbox" id="ch03" checked={pcsCheck.division} onChange={() => setPcsCheck({ ...pcsCheck, division: !pcsCheck.division })} />
          <label htmlFor="ch03">{getMessage('modal.circuit.trestle.setting.power.conditional.select.check1')}</label>
        </div>
        <div className="d-check-box pop">
          <input type="checkbox" id="ch04" checked={pcsCheck.max} onChange={() => setPcsCheck({ ...pcsCheck, max: !pcsCheck.max })} />
          <label className="red" htmlFor="ch04">
            {getMessage('modal.circuit.trestle.setting.power.conditional.select.check2')}
          </label>
        </div>
      </div>
    </>
  )
}
