import { useEffect, useRef, useState } from 'react'

import { useMessage } from '@/hooks/useMessage'
import { usePopup } from '@/hooks/usePopup'

import SizeGuide from '@/components/floor-plan/modal/placementShape/SizeGuide'
import MaterialGuide from '@/components/floor-plan/modal/placementShape/MaterialGuide'
import WithDraggable from '@/components/common/draggable/WithDraggable'

import { useCanvasSetting } from '@/hooks/option/useCanvasSetting'
import { useRecoilValue } from 'recoil'
import { roofMaterialsAtom } from '@/store/settingAtom'
import { useCommonCode } from '@/hooks/common/useCommonCode'
import QSelectBox from '@/components/common/select/QSelectBox'
import { globalLocaleStore } from '@/store/localeAtom'

import { onlyNumberInputChange } from '@/util/input-utils'

export const ROOF_MATERIAL_LAYOUT = {
  PARALLEL: 'P',
  STAIRS: 'S',
}
export default function PlacementShapeSetting({ id, pos = { x: 50, y: 180 }, setShowPlaceShapeModal }) {
  const [showSizeGuideModal, setShowSizeGuidModal] = useState(false)
  const [showMaterialGuideModal, setShowMaterialGuidModal] = useState(false)
  const { closePopup } = usePopup()
  const { getMessage } = useMessage()
  const roofMaterials = useRecoilValue(roofMaterialsAtom)

  const globalLocale = useRecoilValue(globalLocaleStore)
  const { basicSetting, setBasicSettings, basicSettingSave, addedRoofs, setAddedRoofs } = useCanvasSetting()
  const { findCommonCode } = useCommonCode()
  const [raftCodes, setRaftCodes] = useState([]) // 서까래 정보
  const [currentRoof, setCurrentRoof] = useState(addedRoofs[0]) // 현재 선택된 지붕재 정보

  const roofRef = {
    roofCd: useRef(null),
    width: useRef(null),
    length: useRef(null),
    rafter: useRef(null),
    hajebichi: useRef(null),
  }

  // 데이터를 최초 한 번만 조회
  useEffect(() => {
    if (!basicSetting || !currentRoof || Object.keys(currentRoof).length === 0 || Object.keys(basicSetting).length === 0) return
    const raftCodeList = findCommonCode('203800')
    setRaftCodes(raftCodeList)
    // setCurrentRoof({ ...currentRoof, roofSizeSet: basicSetting.roofMaterials.roofSizeSet, roofAngleSet: basicSetting.roofMaterials.roofAngleSet })
  }, [])

  useEffect(() => {
    if (!currentRoof || Object.keys(currentRoof).length === 0) return
    console.log(basicSetting)
    setBasicSettings({
      ...basicSetting,
      roofSizeSet: String(currentRoof.roofSizeSet),
      roofAngleSet: currentRoof.roofAngleSet,
      roofsData: {
        roofApply: true,
        roofSeq: 0,
        roofMatlCd: currentRoof.roofMatlCd,
        roofWidth: currentRoof.width,
        roofHeight: currentRoof.length,
        roofHajebichi: currentRoof.hajebichi,
        roofGap: currentRoof.raft,
        roofLayout: currentRoof.layout,
        roofPitch: currentRoof.pitch,
        roofAngle: currentRoof.angle,
      },
    })
  }, [currentRoof])

  const handleRoofSizeSetChange = (value) => {
    setCurrentRoof({ ...currentRoof, roofSizeSet: value })
  }

  const handleRoofAngleSetChange = (value) => {
    setCurrentRoof({ ...currentRoof, roofAngleSet: value })
  }

  // Function to update the roofType and corresponding values
  const handleRoofTypeChange = (value) => {
    const selectedRoofMaterial = roofMaterials.find((roof) => roof.roofMatlCd === value)
    setCurrentRoof({ ...selectedRoofMaterial, index: 0, roofSizeSet: String(currentRoof.roofSizeSet), roofAngleSet: currentRoof.roofAngleSet })
  }

  const changeInput = (value, e) => {
    const { name } = e.target
    setCurrentRoof({ ...currentRoof, [name]: Number(value) })
  }

  const handleRafterChange = (value) => {
    setCurrentRoof({ ...currentRoof, raft: value })
  }

  const handleRoofLayoutChange = (value) => {
    setCurrentRoof({ ...currentRoof, layout: value })
  }

  const handleSaveBtn = () => {
    const roofInfo = {
      ...currentRoof,
      roofCd: roofRef.roofCd.current?.value,
      width: roofRef.width.current?.value,
      length: roofRef.length.current?.value,
      hajebichi: roofRef.hajebichi.current?.value,
      raft: roofRef.rafter.current?.value,
      selected: true,
      layout: currentRoof.layout,
      index: 0,
    }

    const newAddedRoofs = [...addedRoofs]
    if (addedRoofs.length === 1) {
      newAddedRoofs[0] = { ...roofInfo }
      setAddedRoofs(newAddedRoofs)
    }

    console.log('save Info', {
      ...basicSetting,
      selectedRoofMaterial: {
        // 선택된 지붕재 정보
        roofInfo,
      },
    })

    setBasicSettings({
      ...basicSetting,
      selectedRoofMaterial: {
        // 선택된 지붕재 정보
        ...roofInfo,
      },
      //roofs: addedRoofs,
      roofsData: {
        roofApply: true,
        roofSeq: 0,
        roofMatlCd: currentRoof.roofMatlCd,
        roofWidth: currentRoof.width,
        roofHeight: currentRoof.length,
        roofHajebichi: currentRoof.hajebichi,
        roofGap: currentRoof.raft,
        roofLayout: currentRoof.layout,
        roofSizeSet: currentRoof.roofSizeSet,
        roofAngleSet: currentRoof.roofAngleSet,
        roofPitch: currentRoof.pitch,
        roofAngle: currentRoof.angle,
      },
    })

    basicSettingSave()
  }

  return (
    <WithDraggable isShow={true} pos={pos}>
      <div className={`modal-pop-wrap ll mount`}>
        <div className="modal-head">
          <h1 className="title">{getMessage('plan.menu.placement.surface.initial.setting')}</h1>
          <button className="modal-close" onClick={() => closePopup(id)}>
            닫기
          </button>
        </div>
        <div className="modal-body">
          <div className="placement-table">
            <table>
              <colgroup>
                <col style={{ width: '151px' }} />
                <col />
              </colgroup>
              <tbody>
                <tr>
                  <th>{getMessage('modal.placement.initial.setting.plan.drawing')}</th>
                  <td>{getMessage('modal.placement.initial.setting.plan.drawing.size.stuff')}</td>
                </tr>
                <tr>
                  <th>
                    <div className="tip-wrap">
                      {getMessage('modal.placement.initial.setting.size')}
                      <button className="tooltip" onClick={() => setShowSizeGuidModal(true)}></button>
                    </div>
                  </th>
                  <td>
                    <div className="pop-form-radio">
                      <div className="d-check-radio pop">
                        <input
                          type="radio"
                          name="roofSizeSet"
                          id="ra01"
                          value="1" // roofSizeSet 값이 '1'인 경우
                          checked={currentRoof?.roofSizeSet === '1'} // 선택 여부 확인
                          //onChange={(e) => setBasicSettings({ ...basicSetting, roofSizeSet: e.target.value })} // 상태 업데이트
                          onClick={() => handleRoofSizeSetChange('1')}
                        />
                        <label htmlFor="ra01">{getMessage('modal.placement.initial.setting.size.roof')}</label>
                      </div>
                      <div className="d-check-radio pop">
                        <input
                          type="radio"
                          name="roofSizeSet"
                          id="ra02"
                          value="2" // roofSizeSet 값이 '2'인 경우
                          checked={currentRoof?.roofSizeSet === '2'} // 선택 여부 확인
                          //onChange={(e) => setBasicSettings({ ...basicSetting, roofSizeSet: e.target.value })} // 상태 업데이트
                          onClick={() => handleRoofSizeSetChange('2')}
                        />
                        <label htmlFor="ra02">{getMessage('modal.placement.initial.setting.size.actual')}</label>
                      </div>
                      <div className="d-check-radio pop">
                        <input
                          type="radio"
                          name="roofSizeSet"
                          id="ra03"
                          value="3" // roofSizeSet 값이 '3'인 경우
                          checked={currentRoof?.roofSizeSet === '3'} // 선택 여부 확인
                          //onChange={(e) => setBasicSettings({ ...basicSetting, roofSizeSet: e.target.value })} // 상태 업데이트
                          onClick={() => handleRoofSizeSetChange('3')}
                        />
                        <label htmlFor="ra03">{getMessage('modal.placement.initial.setting.size.none.pitch')}</label>
                      </div>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>{getMessage('modal.placement.initial.setting.roof.angle.setting')}</th>
                  <td>
                    <div className="pop-form-radio">
                      <div className="d-check-radio pop">
                        <input
                          type="radio"
                          name="roofAngleSet"
                          id="ra04"
                          value="slope" // 첫 번째 라디오 버튼의 값
                          checked={currentRoof?.roofAngleSet === 'slope'} // 현재 선택된 값인지 확인
                          //onChange={(e) => setBasicSettings({ ...basicSetting, roofAngleSet: e.target.value })} // 상태 업데이트
                          onClick={() => handleRoofAngleSetChange('slope')}
                        />
                        <label htmlFor="ra04">{getMessage('modal.placement.initial.setting.roof.pitch')}</label>
                      </div>
                      <div className="d-check-radio pop">
                        <input
                          type="radio"
                          name="roofAngleSet"
                          id="ra05"
                          value="flat" // 두 번째 라디오 버튼의 값
                          checked={currentRoof?.roofAngleSet === 'flat'} // 현재 선택된 값인지 확인
                          //onChange={(e) => setBasicSettings({ ...basicSetting, roofAngleSet: e.target.value })} // 상태 업데이트
                          onClick={() => handleRoofAngleSetChange('flat')}
                        />
                        <label htmlFor="ra05">{getMessage('modal.placement.initial.setting.roof.angle')}</label>
                      </div>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>
                    <div className="tip-wrap">
                      {getMessage('modal.placement.initial.setting.roof.material')}
                      <button className="tooltip" onClick={() => setShowMaterialGuidModal(true)}></button>
                    </div>
                  </th>
                  <td>
                    <div className="placement-option">
                      <div className="grid-select no-flx" style={{ width: '171px' }}>
                        <QSelectBox
                          title={
                            currentRoof?.roofSizeSet === '3' ? getMessage('modal.placement.initial.setting.size.none.pitch') : currentRoof?.roofMatlNm
                          }
                          ref={roofRef.roofCd}
                          options={roofMaterials.map((roof, index) => {
                            return { ...roof, name: globalLocale === 'ko' ? roof.roofMatlNm : roof.roofMatlNmJp }
                          })}
                          value={currentRoof?.roofSizeSet === '3' ? null : currentRoof?.roofMatlCd}
                          onChange={(e) => handleRoofTypeChange(e.roofMatlCd)}
                          sourceKey="id"
                          targetKey="id"
                          showKey="name"
                          disabled={currentRoof?.roofSizeSet === '3'}
                        />
                        {/* <select
                          className="select-light dark"
                          name="roofMatlCd"
                          ref={roofRef.roofCd}
                          value={currentRoofMaterial.roofMatlCd}
                          onChange={(e) => {
                            handleRoofTypeChange(e.target.value)
                          }}
                        >
                          {roofMaterials.map((roof, index) => {
                            return (
                              <option key={index} value={roof.roofMatlCd}>
                                {roof.roofMatlNm}
                              </option>
                            )
                          })}
                        </select> */}
                      </div>
                      {currentRoof && ['R', 'C'].includes(currentRoof.widAuth) && (
                        <div className="flex-ment">
                          <span>W</span>
                          <div className="input-grid" style={{ width: '84px' }}>
                            <input
                              type="text"
                              className="input-origin block"
                              name={`width`}
                              ref={roofRef.width}
                              value={parseInt(currentRoof?.width)}
                              onChange={(e) => onlyNumberInputChange(e, changeInput)}
                              readOnly={currentRoof?.widAuth === 'R'}
                              disabled={currentRoof?.roofSizeSet === '3'}
                            />
                          </div>
                          {/* <div className="input-grid" style={{ width: '63px' }}>
                              <input
                                type="text"
                                className="input-origin block"
                                ref={roofRef.width}
                                defaultValue={parseInt(currentRoofMaterial.width)}
                              />
                            </div> */}
                        </div>
                      )}
                      {currentRoof && ['R', 'C'].includes(currentRoof.lenAuth) && (
                        <div className="flex-ment">
                          <span>L</span>
                          <div className="input-grid" style={{ width: '84px' }}>
                            <input
                              type="text"
                              className="input-origin block"
                              name={`length`}
                              ref={roofRef.length}
                              value={parseInt(currentRoof?.length)}
                              onChange={(e) => onlyNumberInputChange(e, changeInput)}
                              readOnly={currentRoof?.lenAuth === 'R'}
                              disabled={currentRoof?.roofSizeSet === '3'}
                            />
                          </div>
                          {/* <div className="input-grid" style={{ width: '63px' }}>
                            <input
                              type="text"
                              className="input-origin block"
                              ref={roofRef.length}
                              defaultValue={parseInt(currentRoofMaterial.length)}
                            />
                          </div> */}
                        </div>
                      )}
                      {currentRoof && ['C', 'R'].includes(currentRoof.raftAuth) && (
                        <div className="flex-ment">
                          <span>{getMessage('modal.placement.initial.setting.rafter')}</span>
                          {raftCodes.length > 0 && (
                            <div className="select-wrap" style={{ width: '160px' }}>
                              <QSelectBox
                                options={raftCodes}
                                ref={roofRef.rafter}
                                title={
                                  raftCodes.find((r) => r.clCode === (currentRoof?.raft === undefined ? currentRoof?.raftBaseCd : currentRoof?.raft))
                                    .clCodeNm
                                }
                                value={currentRoof?.raft === undefined ? currentRoof?.raftBaseCd : currentRoof?.raft}
                                onChange={(e) => handleRafterChange(e.clCode)}
                                sourceKey="clCode"
                                targetKey={currentRoof?.raft ? 'raft' : 'raftBaseCd'}
                                showKey="clCodeNm"
                                disabled={currentRoof?.roofSizeSet === '3'}
                              />
                              {/* <select className="select-light dark" name="roofGap" ref={roofRef.rafter}>
                              {raftCodes.map((raft, index) => {
                                return (
                                  <option key={index} value={raft.clCode} selected={currentRoofMaterial.raft === raft.clCode}>
                                    {raft.clCodeNm}
                                  </option>
                                )
                              })}
                            </select> */}
                            </div>
                          )}
                        </div>
                      )}
                      {currentRoof && ['C', 'R'].includes(currentRoof.roofPchAuth) && (
                        <div className="flex-ment">
                          <span>{getMessage('hajebichi')}</span>
                          <div className="input-grid" style={{ width: '84px' }}>
                            <input
                              type="text"
                              className="input-origin block"
                              name={`hajebichi`}
                              ref={roofRef.hajebichi}
                              value={parseInt(currentRoof.hajebichi)}
                              onChange={(e) => onlyNumberInputChange(e, changeInput)}
                              readOnly={currentRoof.roofPchAuth === 'R'}
                              disabled={currentRoof.roofSizeSet === '3'}
                            />
                          </div>
                        </div>
                      )}
                    </div>
                    {currentRoof && (
                      <div className="placement-roof-btn-wrap">
                        <div className="icon-btn-wrap mt10">
                          <button
                            className={`${currentRoof?.layout === ROOF_MATERIAL_LAYOUT.PARALLEL && 'act'}`}
                            value={ROOF_MATERIAL_LAYOUT.PARALLEL}
                            onClick={() => handleRoofLayoutChange(ROOF_MATERIAL_LAYOUT.PARALLEL)}
                          >
                            {getMessage('modal.roof.alloc.select.parallel')}
                            <i className="allocation01"></i>
                          </button>
                          <button
                            className={`${currentRoof.layout === ROOF_MATERIAL_LAYOUT.STAIRS && 'act'}`}
                            value={ROOF_MATERIAL_LAYOUT.STAIRS}
                            onClick={() => handleRoofLayoutChange(ROOF_MATERIAL_LAYOUT.STAIRS)}
                          >
                            {getMessage('modal.roof.alloc.select.stairs')} <i className="allocation02"></i>
                          </button>
                        </div>
                      </div>
                    )}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div className="grid-btn-wrap">
            <button className="btn-frame modal act" onClick={handleSaveBtn}>
              {getMessage('modal.common.save')}
            </button>
          </div>
        </div>
        {showSizeGuideModal && <SizeGuide setShowSizeGuidModal={setShowSizeGuidModal} />}
        {showMaterialGuideModal && <MaterialGuide setShowMaterialGuidModal={setShowMaterialGuidModal} />}
      </div>
    </WithDraggable>
  )
}
