import { GlobalDataContext } from '@/app/GlobalDataProvider'
import QSelectBox from '@/components/common/select/QSelectBox'
import { useMasterController } from '@/hooks/common/useMasterController'
import { useEvent } from '@/hooks/useEvent'
import { useMessage } from '@/hooks/useMessage'
import { useSwal } from '@/hooks/useSwal'
import { makerState, modelState, pcsCheckState, seriesState } from '@/store/circuitTrestleAtom'
import { globalLocaleStore } from '@/store/localeAtom'
import { moduleSelectionDataState, selectedModuleState } from '@/store/selectedModuleOptions'
import { useContext, useEffect, useState } from 'react'
import { useRecoilState } from 'recoil'
import { useRecoilValue } from 'recoil'
import { v4 as uuidv4 } from 'uuid'

export default function PowerConditionalSelect(props) {
  let { tabNum, setTabNum } = props
  const [makerData, setMakerData] = useRecoilState(makerState)
  const [makers, setMakers] = useState(makerData.makers)
  const [selectedMaker, setSelectedMaker] = useState(makerData.selectedMaker)
  const [series, setSeries] = useRecoilState(seriesState)
  const [seriesList, setSeriesList] = useState(series.series)
  const [selectedSeries, setSelectedSeries] = useState(series.selectedSeries)
  const [model, setModel] = useRecoilState(modelState)
  const [models, setModels] = useState(model.models)
  const [selectedModels, setSelectedModels] = useState(model.selectedModels)
  const [pcsCheck, setPcsCheck] = useRecoilState(pcsCheckState)
  const { managementState, setManagementState, managementStateLoaded } = useContext(GlobalDataContext)
  const { getMessage } = useMessage()
  const [selectedRow, setSelectedRow] = useState(null)
  const globalLocale = useRecoilValue(globalLocaleStore)
  const { getPcsMakerList, getPcsModelList } = useMasterController()
  const selectedModules = useRecoilValue(selectedModuleState)
  const { swalFire } = useSwal()
  const modelHeader = [
    { name: getMessage('명칭'), width: '15%', prop: 'itemNm', 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(() => {
    if (makers.length === 0) {
      getPcsMakerList().then((res) => {
        setMakers(res.data)
      })
    }
    console.log('🚀 ~ useEffect ~ selectedModules:', selectedModules)
    if (!managementState) {
      setManagementState(managementStateLoaded)
    }
    // promiseGet({ url: `/api/object/${correntObjectNo}/detail` }).then((res) => {
    //   console.log('🚀 ~ useEffect ~ /api/object/${correntObjectNo}/detail:', res)
    //   // coldRegionFlg-한랭지사양, conType// 계약조건(잉여~,전량)
    // })
    return () => {
      setMakerData({ makers, selectedMaker })
      setSeries({ series: seriesList, selectedSeries })
      setModel({ models, selectedModels })
    }
  }, [])

  useEffect(() => {
    console.log('🚀 ~ PowerConditionalSelect ~ selectedMaker:', selectedMaker)
    if (selectedMaker) {
      setSelectedModels([])
      setModels([])
      getPcsMakerList(selectedMaker).then((res) => {
        setSeriesList(
          res.data.map((series) => {
            return { ...series, selected: false }
          }),
        )
      })
    }
  }, [selectedMaker])

  useEffect(() => {
    if (seriesList.filter((series) => series.selected).length === 0) return
    const pcsMkrCd = seriesList.filter((series) => series.selected)[0]?.pcsMkrCd
    const pcsSerList = seriesList
      .filter((series) => series.selected)
      .map((series) => {
        return { pcsSerCd: series.pcsSerCd }
      })
    const moduleItemList = selectedModules.itemList?.map((module) => {
      return {
        itemId: module.itemId,
        mixMatlNo: module.mixMatlNo,
      }
    })
    getPcsModelList({ pcsMkrCd, pcsSerList, moduleItemList }).then((res) => {
      if (res?.result.code === 200) {
        console.log('🚀 ~ useEffect ~ res:', res.data)
        setModels(
          res.data.map((model) => {
            return {
              ...model,
              moduleStdQty: parseInt(model.moduleStdQty),
              moduleMaxQty: parseInt(model.moduleMaxQty),
              code: uuidv4(),
              selected: false,
            }
          }),
        )
      }
    })
  }, [seriesList])

  useEffect(() => {
    console.log('🚀 ~ useEffect ~ models:', models)
  }, [models])

  useEffect(() => {
    console.log('🚀 ~ useEffect ~ pcsCheck:', pcsCheck)
  }, [pcsCheck])

  const onCheckSeries = (series) => {
    setSeriesList((prev) => prev.map((s) => ({ ...s, selected: s.pcsSerCd === series.pcsSerCd ? !s.selected : s.selected })))
  }

  const onAddSelectedModel = () => {
    if (selectedRow === null) return
    if (selectedModels.length === 3) {
      swalFire({
        title: '최대 3개까지 선택할 수 있습니다.',
        icon: 'warning',
      })

      return
    }
    setSelectedModels([...selectedModels, selectedRow])
    setSelectedRow(null)
  }

  const onRemoveSelectedModel = (model) => {
    setSelectedModels(selectedModels.filter((m) => m.code !== model.code))
  }

  useEffect(() => {
    console.log('🚀 ~ useEffect ~ selectedModels:', selectedModels)
    const selectedModelsIds = selectedModels.map((model) => model.code)

    setModels(
      models.map((model) => {
        return {
          ...model,
          selected: selectedModelsIds.includes(model.code),
        }
      }),
    )
    setModel({ ...model, selectedModels: selectedModels })
  }, [selectedModels])
  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) => setSelectedMaker(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">
            {seriesList?.map((series, index) => (
              <div className="d-check-box pop sel">
                <input type="checkbox" id={`"ch0"${index}`} onClick={() => 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
                    ?.filter((model) => !model.selected)
                    .map((model, index) => (
                      <tr key={index} onClick={() => setSelectedRow(model)} className={model === selectedRow ? 'on' : ''}>
                        {modelHeader.map((header) => (
                          <td>{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) => (
              <span className="normal-font">
                {model.itemNm} <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>
      {/* <div className="grid-btn-wrap">
        <button className="btn-frame modal mr5" onClick={() => setTabNum(2)}>
          {getMessage('modal.circuit.trestle.setting.circuit.allocation.auto')}
        </button>
        <button className="btn-frame modal act" onClick={() => setTabNum(tabNum + 1)}>
          {getMessage('modal.circuit.trestle.setting.circuit.allocation.passivity')}
        </button>
      </div> */}
    </>
  )
}
