'use client'

import { useEffect, useState } from 'react'
import MenuDepth01 from './MenuDepth01'
import QSelectBox from '@/components/common/select/QSelectBox'
import { useMessage } from '@/hooks/useMessage'
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil'
import { settingModalFirstOptionsState, settingModalSecondOptionsState } from '@/store/settingAtom'
import { canvasState, canvasZoomState, currentMenuState, verticalHorizontalModeState } from '@/store/canvasAtom'
import { outerLinePointsState } from '@/store/outerLineAtom'
import { appMessageStore, globalLocaleStore } from '@/store/localeAtom'
import { MENU } from '@/common/common'

import { useAxios } from '@/hooks/useAxios'
import { toastUp } from '@/hooks/useToast'

import KO from '@/locales/ko.json'
import JA from '@/locales/ja.json'

export default function CanvasMenu(props) {
  const [objectNo, setObjectNo] = useState('test123240912001') // 이후 삭제 필요
  const { setShowCanvasSettingModal, showOutlineModal, setShowOutlineModal } = props
  const [menuNumber, setMenuNumber] = useState(null)
  const [verticalHorizontalMode, setVerticalHorizontalMode] = useRecoilState(verticalHorizontalModeState)
  const [type, setType] = useState('')
  const { getMessage } = useMessage()
  const canvasZoom = useRecoilValue(canvasZoomState)
  const canvas = useRecoilValue(canvasState)
  const setCurrentMenu = useSetRecoilState(currentMenuState)
  const setPoints = useSetRecoilState(outerLinePointsState)
  const globalLocale = useRecoilValue(globalLocaleStore)
  const [appMessageState, setAppMessageState] = useRecoilState(appMessageStore)
  const { post } = useAxios()

  const SelectOption = [{ name: '瓦53A' }, { name: '瓦53A' }]
  const onClickNav = (number) => {
    setMenuNumber(number)
    if (number === 2) setType('outline')
    if (number === 3) setType('surface')
    if (number === 4) setType('module')
  }
  const menuProps = {
    setShowOutlineModal,
    type,
  }

  const firstOptions = useRecoilState(settingModalFirstOptionsState)
  const secondOptions = useRecoilState(settingModalSecondOptionsState)

  useEffect(() => {
    if (globalLocale === 'ko') {
      setAppMessageState(KO)
    } else {
      setAppMessageState(JA)
    }
  }, [menuNumber, type, globalLocale])

  // 저장버튼(btn08) 클릭 시 호출되는 함수
  const handleSaveSettings = async () => {
    try {
      // 서버에 전송할 데이터
      const dataToSend = {
        firstOption1: firstOptions[0].option1.map((item) => ({
          column: item.column,
          selected: item.selected,
        })),
        firstOption2: firstOptions[0].option2.map((item) => ({
          column: item.column,
          selected: item.selected,
        })),
        // secondOption1: secondOptions[0].option1.map((item) => ({
        //   name: item.name,
        //   // 필요한 경우 추가 데이터 항목
        // })),
        secondOption2: secondOptions[0].option2.map((item) => ({
          column: item.column,
          selected: item.selected,
        })),
      }

      const patternData = {
        objectNo,
        //디스플레이 설정(다중)
        assignDisplay: dataToSend.firstOption1[0].selected,
        drawDisplay: dataToSend.firstOption1[1].selected,
        gridDisplay: dataToSend.firstOption1[2].selected,
        charDisplay: dataToSend.firstOption1[3].selected,
        flowDisplay: dataToSend.firstOption1[4].selected,
        hallwayDimenDisplay: dataToSend.firstOption1[5].selected,
        actualDimenDisplay: dataToSend.firstOption1[6].selected,
        noDimenDisplay: dataToSend.firstOption1[7].selected,
        trestleDisplay: dataToSend.firstOption1[8].selected,
        coordiDisplay: dataToSend.firstOption1[9].selected,
        drawConverDisplay: dataToSend.firstOption1[10].selected,
        //화면 표시(다중)
        onlyBorder: dataToSend.firstOption2[0].selected,
        lineHatch: dataToSend.firstOption2[1].selected,
        allPainted: dataToSend.firstOption2[2].selected,
        //흡착범위 설정(단건)
        adsorpRangeSmall: dataToSend.secondOption2[0].selected,
        adsorpRangeSmallSemi: dataToSend.secondOption2[1].selected,
        adsorpRangeMedium: dataToSend.secondOption2[2].selected,
        adsorpRangeLarge: dataToSend.secondOption2[3].selected,
      }

      // HTTP POST 요청 보내기
      await post({ url: `/api/canvas-management/canvas-settings`, data: patternData }).then((res) => {
        toastUp({ message: res.returnMessage, type: 'success' })
      })
    } catch (error) {
      toastUp({ message: res.returnMessage, type: 'error' })
    }
  }

  const handleClear = () => {
    setPoints([])
    canvas?.clear()
  }

  return (
    <div className={`canvas-menu-wrap ${menuNumber === 2 || menuNumber === 3 || menuNumber === 4 ? 'active' : ''}`}>
      <div className="canvas-menu-inner">
        <ul className="canvas-menu-list">
          <li className={`canvas-menu-item ${menuNumber === 0 ? 'active' : ''}`} onClick={() => onClickNav(0)}>
            <button>
              <span className="menu-icon con00"></span>
              {getMessage('plan.menu.plan.drawing')}
            </button>
          </li>
          <li className={`canvas-menu-item ${menuNumber === 1 ? 'active' : ''}`} onClick={() => onClickNav(1)}>
            <button>
              <span className="menu-icon con01"></span>
              {getMessage('plan.menu.placement.surface.initial.setting')}
            </button>
          </li>
          <li
            className={`canvas-menu-item ${menuNumber === 2 ? 'active' : ''}`}
            onClick={() => {
              onClickNav(2)
              setCurrentMenu(MENU.ROOF_COVERING.DEFAULT)
            }}
          >
            <button>
              <span className="menu-icon con02"></span>
              {getMessage('plan.menu.roof.cover')}
            </button>
          </li>
          <li
            className={`canvas-menu-item ${menuNumber === 3 ? 'active' : ''}`}
            onClick={() => {
              onClickNav(3)
              setCurrentMenu(MENU.BATCH_CANVAS.DEFAULT)
            }}
          >
            <button>
              <span className="menu-icon con03"></span>
              {getMessage('plan.menu.placement.surface')}
            </button>
          </li>
          <li
            className={`canvas-menu-item ${menuNumber === 4 ? 'active' : ''}`}
            onClick={() => {
              onClickNav(4)
              setCurrentMenu(MENU.MODULE_CIRCUIT_SETTING.DEFAULT)
            }}
          >
            <button>
              <span className="menu-icon con04"></span>
              {getMessage('plan.menu.module.circuit.setting')}
            </button>
          </li>
          <li
            className={`canvas-menu-item ${menuNumber === 5 ? 'active' : ''}`}
            onClick={() => {
              onClickNav(5)
              setCurrentMenu(MENU.ESTIMATE.DEFAULT)
            }}
          >
            <button>
              <span className="menu-icon con06"></span>
              {getMessage('plan.menu.estimate')}
            </button>
          </li>
          <li
            className={`canvas-menu-item ${menuNumber === 6 ? 'active' : ''}`}
            onClick={() => {
              onClickNav(6)
              setCurrentMenu(MENU.POWER_GENERATION_SIMULATION.DEFAULT)
            }}
          >
            <button>
              <span className="menu-icon con05"></span>
              {getMessage('plan.menu.simulation')}
            </button>
          </li>
        </ul>
        <div className="canvas-side-btn-wrap">
          {menuNumber !== 6 && menuNumber !== 5 && (
            <>
              <div className="btn-from">
                <button className="btn01"></button>
                <button className="btn02 active"></button>
                <button className="btn03 "></button>
              </div>
              {menuNumber !== 4 && (
                <div className={`vertical-horizontal ${verticalHorizontalMode ? 'on' : ''}`}>
                  <span>{getMessage('plan.mode.vertical.horizontal')}</span>
                  <button onClick={() => setVerticalHorizontalMode(!verticalHorizontalMode)}>{verticalHorizontalMode ? 'ON' : 'OFF'}</button>
                </div>
              )}
              <div className="select-box">
                <QSelectBox title={'瓦53A'} option={SelectOption} />
              </div>
              <div className="btn-from">
                <button className="btn04" onClick={() => setShowCanvasSettingModal(true)}></button>
                <button className="btn05"></button>
                <button className="btn06"></button>
              </div>
              <div className="size-control">
                <button className="control-btn minus"></button>
                <span>{canvasZoom}%</span>
                <button className="control-btn plus"></button>
              </div>
              <div className="btn-from">
                <button className="btn07" onClick={handleClear}></button>
                <button className="btn08" onClick={handleSaveSettings}></button>
                <button className="btn09"></button>
              </div>
            </>
          )}

          {menuNumber === 5 && (
            <>
              <div className="ico-btn-from">
                <button className="btn-frame gray ico-flx act">
                  <span className="ico ico01"></span>
                  <span>{getMessage('plan.menu.estimate.roof.alloc')}</span>
                </button>
                <button className="btn-frame gray ico-flx">
                  <span className="ico ico02"></span>
                  <span>{getMessage('plan.menu.estimate.save')}</span>
                </button>
                <button className="btn-frame gray ico-flx">
                  <span className="ico ico03"></span>
                  <span>{getMessage('plan.menu.estimate.reset')}</span>
                </button>
                <button className="btn-frame gray ico-flx">
                  <span className="ico ico04"></span>
                  <span>{getMessage('plan.menu.estimate.copy')}</span>
                </button>
              </div>
            </>
          )}
          {menuNumber === 6 && (
            <>
              <div className="ico-btn-from">
                <button className="btn-frame gray ico-flx">
                  <span className="ico ico01"></span>
                  <span>{getMessage('plan.menu.simulation.excel')}</span>
                </button>
                <button className="btn-frame gray ico-flx">
                  <span className="ico ico01"></span>
                  <span>{getMessage('plan.menu.simulation.pdf')}</span>
                </button>
              </div>
            </>
          )}
        </div>
      </div>
      <div className={`canvas-depth2-wrap ${menuNumber === 2 || menuNumber === 3 || menuNumber === 4 ? 'active' : ''}`}>
        {(menuNumber === 2 || menuNumber === 3 || menuNumber === 4) && <MenuDepth01 {...menuProps} />}
      </div>
    </div>
  )
}
