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 { useRecoilState } from 'recoil'
import { Fragment, useEffect, useState } from 'react'
import { canvasSettingState } from '@/store/canvasAtom'
import { useMessage } from '@/hooks/useMessage'
import { useAxios } from '@/hooks/useAxios'
import { useSwal } from '@/hooks/useSwal'
import { usePopup } from '@/hooks/usePopup'
import { basicSettingState } from '@/store/settingAtom'
import useRefFiles from '@/hooks/common/useRefFiles'

export default function PlacementShapeSetting({ id, pos = { x: 50, y: 180 }, setShowPlaceShapeModal }) {
  const [objectNo, setObjectNo] = useState('test123241008001') // 후에 삭제 필요
  const [showSizeGuideModal, setShowSizeGuidModal] = useState(false)
  const [showMaterialGuideModal, setShowMaterialGuidModal] = useState(false)
  const [selectedRoofMaterial, setSelectedRoofMaterial] = useState(1)
  const [canvasSetting, setCanvasSetting] = useRecoilState(canvasSettingState)
  const { closePopup } = usePopup()
  const [basicSetting, setBasicSettings] = useRecoilState(basicSettingState)
  const { refImage, setRefImage, handleRefFile } = useRefFiles()

  const { getMessage } = useMessage()
  const { get, post } = useAxios()
  const { swalFire } = useSwal()

  // 데이터를 최초 한 번만 조회
  useEffect(() => {
    console.log('PlacementShapeSetting useEffect 실행')

    fetchSettings()
  }, [objectNo])

  // PlacementShapeSetting 조회 및 초기화
  const fetchSettings = async () => {
    try {
      await get({ url: `/api/canvas-management/canvas-basic-settings/by-object/${objectNo}` }).then((res) => {
        if (res.length == 0) return

        // 'roofs' 배열을 생성하여 각 항목을 추가
        const roofsRow = res.map((item) => {
          return {
            roofSizeSet: item.roofSizeSet,
            roofAngleSet: item.roofAngleSet,
          }
        })

        const roofsArray = res.some((item) => !item.roofSeq)
          ? //최초 지붕재 추가 정보의 경우 roofsArray를 초기화 설정
            res.map(() => ({
              roofApply: true,
              roofSeq: 1,
              roofType: 1,
              roofWidth: 200,
              roofHeight: 200,
              roofHajebichi: 200,
              roofGap: 0,
              roofLayout: 'parallel',
            }))
          : res.map((item) => ({
              roofApply: item.roofApply === '' || item.roofApply === false ? false : true,
              roofSeq: item.roofSeq,
              roofType: item.roofType,
              roofWidth: item.roofWidth,
              roofHeight: item.roofHeight,
              roofHajebichi: item.roofHajebichi,
              roofGap: item.roofGap,
              roofLayout: item.roofLayout,
            }))
        console.log('roofsArray ', roofsArray)
        // 나머지 데이터와 함께 'roofs' 배열을 patternData에 넣음
        const patternData = {
          roofSizeSet: roofsRow[0].roofSizeSet, // 첫 번째 항목의 값을 사용
          roofAngleSet: roofsRow[0].roofAngleSet, // 첫 번째 항목의 값을 사용
          roofs: roofsArray, // 만들어진 roofs 배열
        }

        // 데이터 설정
        setBasicSettings({ ...patternData })
      })
    } catch (error) {
      console.error('Data fetching error:', error)
    }

    if (!(Object.keys(canvasSetting).length === 0 && canvasSetting.constructor === Object)) {
      setBasicSettings({ ...canvasSetting })
    }
  }

  const submitCanvasConfig = async () => {
    try {
      const patternData = {
        objectNo,
        roofSizeSet: basicSetting.roofSizeSet,
        roofAngleSet: basicSetting.roofAngleSet,
        roofMaterialsAddList: basicSetting.roofs,
      }

      await post({ url: `/api/canvas-management/canvas-basic-settings`, data: patternData }).then((res) => {
        swalFire({ text: getMessage(res.returnMessage) })
      })

      //Recoil 설정
      setCanvasSetting({ ...basicSetting })
    } catch (error) {
      swalFire({ text: getMessage(res.returnMessage), icon: 'error' })
    }
  }

  // Function to update the roofType and corresponding values
  const handleRoofTypeChange = (index, value) => {
    const updatedRoofs = [...basicSetting.roofs]
    const roofType = parseInt(value, 10)

    // Reset other values based on the selected roofType
    if (roofType === 1) {
      updatedRoofs[index] = {
        ...updatedRoofs[index],
        roofType: 1,
        roofWidth: 265,
        roofHeight: 235,
        roofGap: 455,
        hajebichi: 0,
      }
    } else if (roofType === 2) {
      updatedRoofs[index] = {
        ...updatedRoofs[index],
        roofType: 2,
        roofGap: 265,
        roofHajebichi: 265,
        roofWidth: 0,
        roofHeight: 0,
      }
    } else if (roofType === 3) {
      updatedRoofs[index] = {
        ...updatedRoofs[index],
        roofType: 3,
        roofHajebichi: 265,
        roofGap: 0,
        roofWidth: 0,
        roofHeight: 0,
      }
    } else if (roofType === 4) {
      updatedRoofs[index] = {
        ...updatedRoofs[index],
        roofType: 4,
        roofHeight: 265,
        roofGap: 265,
        roofHajebichi: 0,
        roofWidth: 0,
      }
    }

    setBasicSettings({
      ...basicSetting,
      roofs: updatedRoofs,
    })
  }

  return (
    <WithDraggable isShow={true} pos={pos}>
      <div className={`modal-pop-wrap l 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>
                    {getMessage('modal.placement.initial.setting.size')}
                    <button className="tooltip" onClick={() => setShowSizeGuidModal(true)}></button>
                  </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={basicSetting.roofSizeSet == '1'} // 선택 여부 확인
                          onChange={(e) => setBasicSettings({ ...basicSetting, roofSizeSet: e.target.value })} // 상태 업데이트
                        />
                        <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={basicSetting.roofSizeSet == '2'} // 선택 여부 확인
                          onChange={(e) => setBasicSettings({ ...basicSetting, roofSizeSet: e.target.value })} // 상태 업데이트
                        />
                        <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={basicSetting.roofSizeSet == '3'} // 선택 여부 확인
                          onChange={(e) => setBasicSettings({ ...basicSetting, roofSizeSet: e.target.value })} // 상태 업데이트
                        />
                        <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={basicSetting.roofAngleSet == 'slope'} // 현재 선택된 값인지 확인
                          onChange={(e) => setBasicSettings({ ...basicSetting, roofAngleSet: e.target.value })} // 상태 업데이트
                        />
                        <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={basicSetting.roofAngleSet == 'flat'} // 현재 선택된 값인지 확인
                          onChange={(e) => setBasicSettings({ ...basicSetting, roofAngleSet: e.target.value })} // 상태 업데이트
                        />
                        <label htmlFor="ra05">{getMessage('modal.placement.initial.setting.roof.angle')}</label>
                      </div>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>
                    {getMessage('modal.placement.initial.setting.roof.material')}
                    <button className="tooltip" onClick={() => setShowMaterialGuidModal(true)}></button>
                  </th>
                  <td>
                    <div className="placement-option">
                      <div className="select-wrap" style={{ width: '171px' }}>
                        <select
                          className="select-light dark"
                          name="roofType"
                          value={basicSetting.roofs[0].roofType}
                          onChange={(e) => handleRoofTypeChange(0, e.target.value)}
                        >
                          <option value="1">瓦 type A</option>
                          <option value="2">瓦 type B</option>
                          <option value="3">瓦 type C</option>
                          <option value="4">瓦 type D</option>
                        </select>
                      </div>
                      {basicSetting.roofs[0].roofType === 1 ? (
                        <>
                          <div className="flex-ment">
                            <span>W</span>
                            <div className="select-wrap" style={{ width: '84px' }}>
                              <select
                                className="select-light dark"
                                name="roofWidth"
                                value={basicSetting.roofs[0].roofWidth}
                                onChange={(e) => {
                                  // 상태 업데이트 함수 호출
                                  setBasicSettings({
                                    ...basicSetting,
                                    roofs: [
                                      {
                                        ...basicSetting.roofs[0],
                                        roofWidth: e.target.value,
                                      },
                                    ],
                                  })
                                }}
                              >
                                <option>265</option>
                              </select>
                            </div>
                          </div>
                          <div className="flex-ment">
                            <span>L</span>
                            <div className="select-wrap" style={{ width: '84px' }}>
                              <select
                                className="select-light dark"
                                name="roofHeight"
                                value={basicSetting.roofs[0].roofHeight}
                                onChange={(e) => {
                                  // 상태 업데이트 함수 호출
                                  setBasicSettings({
                                    ...basicSetting,
                                    roofs: [
                                      {
                                        ...basicSetting.roofs[0],
                                        roofHeight: e.target.value,
                                      },
                                    ],
                                  })
                                }}
                              >
                                <option>235</option>
                              </select>
                            </div>
                          </div>
                          <div className="flex-ment">
                            <span>{getMessage('modal.placement.initial.setting.rafter')}</span>
                            <div className="select-wrap" style={{ width: '84px' }}>
                              <select
                                className="select-light dark"
                                name="roofGap"
                                value={basicSetting.roofs[0].roofGap}
                                onChange={(e) => {
                                  // 상태 업데이트 함수 호출
                                  setBasicSettings({
                                    ...basicSetting,
                                    roofs: [
                                      {
                                        ...basicSetting.roofs[0],
                                        roofGap: e.target.value,
                                      },
                                    ],
                                  })
                                }}
                              >
                                <option>455</option>
                              </select>
                            </div>
                          </div>
                        </>
                      ) : basicSetting.roofs[0].roofType === 2 ? (
                        <>
                          <div className="flex-ment">
                            <span>{getMessage('hajebichi')}</span>
                            <div className="grid-select no-flx" style={{ width: '84px' }}>
                              <select
                                className="select-light dark"
                                name="roofHajebichi"
                                value={basicSetting.roofs[0].roofHajebichi}
                                onChange={(e) => {
                                  // 상태 업데이트 함수 호출
                                  setBasicSettings({
                                    ...basicSetting,
                                    roofs: [
                                      {
                                        ...basicSetting.roofs[0],
                                        roofHajebichi: e.target.value,
                                      },
                                    ],
                                  })
                                }}
                              >
                                <option>265</option>
                              </select>
                            </div>
                          </div>
                          <div className="flex-ment">
                            <span>{getMessage('modal.placement.initial.setting.rafter')}</span>
                            <div className="grid-select no-flx right" style={{ width: '84px' }}>
                              <select
                                className="select-light dark"
                                name="roofGap"
                                value={basicSetting.roofs[0].roofGap}
                                onChange={(e) => {
                                  // 상태 업데이트 함수 호출
                                  setBasicSettings({
                                    ...basicSetting,
                                    roofs: [
                                      {
                                        ...basicSetting.roofs[0],
                                        roofGap: e.target.value,
                                      },
                                    ],
                                  })
                                }}
                              >
                                <option>265</option>
                              </select>
                            </div>
                          </div>
                        </>
                      ) : basicSetting.roofs[0].roofType === 3 ? (
                        <>
                          <div className="flex-ment">
                            <span>{getMessage('hajebichi')}</span>
                            <div className="grid-select no-flx" style={{ width: '84px' }}>
                              <select
                                className="select-light dark"
                                name="roofHajebichi"
                                value={basicSetting.roofs[0].roofHajebichi}
                                onChange={(e) => {
                                  // 상태 업데이트 함수 호출
                                  setBasicSettings({
                                    ...basicSetting,
                                    roofs: [
                                      {
                                        ...basicSetting.roofs[0],
                                        roofHajebichi: e.target.value,
                                      },
                                    ],
                                  })
                                }}
                              >
                                <option>265</option>
                              </select>
                            </div>
                          </div>
                        </>
                      ) : basicSetting.roofs[0].roofType === 4 ? (
                        <>
                          <div className="flex-ment">
                            <span>L</span>
                            <div className="grid-select no-flx" style={{ width: '84px' }}>
                              <select
                                className="select-light dark"
                                name="roofHeight"
                                value={basicSetting.roofs[0].roofHeight}
                                onChange={(e) => {
                                  // 상태 업데이트 함수 호출
                                  setBasicSettings({
                                    ...basicSetting,
                                    roofs: [
                                      {
                                        ...basicSetting.roofs[0],
                                        roofHeight: e.target.value,
                                      },
                                    ],
                                  })
                                }}
                              >
                                <option>265</option>
                              </select>
                            </div>
                          </div>
                          <div className="flex-ment">
                            <span>{getMessage('modal.placement.initial.setting.rafter')}</span>
                            <div className="grid-select no-flx right" style={{ width: '84px' }}>
                              <select
                                className="select-light dark"
                                name="roofGap"
                                value={basicSetting.roofs[0].roofGap}
                                onChange={(e) => {
                                  // 상태 업데이트 함수 호출
                                  setBasicSettings({
                                    ...basicSetting,
                                    roofs: [
                                      {
                                        ...basicSetting.roofs[0],
                                        roofGap: e.target.value,
                                      },
                                    ],
                                  })
                                }}
                              >
                                <option>265</option>
                              </select>
                            </div>
                          </div>
                        </>
                      ) : (
                        ''
                      )}
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>{getMessage('common.input.file')}</th>
                  <td>
                    <div className="flex-box">
                      <div className="img-edit-wrap">
                        <label className="img-edit-btn" htmlFor="img_file">
                          <span className="img-edit"></span>
                          {getMessage('common.input.file.load')}
                        </label>
                        <input type="file" id="img_file" style={{ display: 'none' }} onChange={(e) => handleRefFile(e.target.files[0])} />
                      </div>
                      <div className="img-name-wrap">
                        <input type="text" className="input-origin al-l" defaultValue={''} value={refImage ? refImage.name : ''} readOnly />
                        {refImage && <button className="img-check" onClick={() => setRefImage(null)}></button>}
                      </div>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div className="grid-btn-wrap">
            <button className="btn-frame modal act" onClick={() => submitCanvasConfig()}>
              {getMessage('modal.common.save')}
            </button>
          </div>
        </div>
        {showSizeGuideModal && <SizeGuide setShowSizeGuidModal={setShowSizeGuidModal} />}
        {showMaterialGuideModal && <MaterialGuide setShowMaterialGuidModal={setShowMaterialGuidModal} />}
      </div>
    </WithDraggable>
  )
}
