'use client'

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

import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil'

import { usePathname, useRouter } from 'next/navigation'
import MenuDepth01 from './MenuDepth01'
import QSelectBox from '@/components/common/select/QSelectBox'
import { v4 as uuidv4 } from 'uuid'
import { useMessage } from '@/hooks/useMessage'
import { usePlan } from '@/hooks/usePlan'
import { useSwal } from '@/hooks/useSwal'
import { useEvent } from '@/hooks/useEvent'
import { canvasSettingState, canvasState, canvasZoomState, currentMenuState, verticalHorizontalModeState } from '@/store/canvasAtom'
import { sessionStore } from '@/store/commonAtom'
import { outerLinePointsState } from '@/store/outerLineAtom'
import { appMessageStore, globalLocaleStore } from '@/store/localeAtom'
import { settingModalFirstOptionsState } from '@/store/settingAtom'

import KO from '@/locales/ko.json'
import JA from '@/locales/ja.json'
import { useCanvasEvent } from '@/hooks/useCanvasEvent'
import SettingModal01 from '@/components/floor-plan/modal/setting01/SettingModal01'
import { usePopup } from '@/hooks/usePopup'
import { placementShapeDrawingPointsState } from '@/store/placementShapeDrawingAtom'
import PlacementShapeSetting from '@/components/floor-plan/modal/placementShape/PlacementShapeSetting'
import { useCommonUtils } from '@/hooks/common/useCommonUtils'

import { commonUtilsState } from '@/store/commonUtilsAtom'
import { menusState, menuTypeState } from '@/store/menuAtom'
import useMenu from '@/hooks/common/useMenu'
import { MENU } from '@/common/common'

import { useEstimateController } from '@/hooks/floorPlan/estimate/useEstimateController'
import { estimateState, floorPlanObjectState } from '@/store/floorPlanObjectAtom'
import DocDownOptionPop from '../estimate/popup/DocDownOptionPop'
import { FloorPlanContext } from '@/app/floor-plan/FloorPlanProvider'
import EstimateCopyPop from '../estimate/popup/EstimateCopyPop'
import { pwrGnrSimTypeState } from '@/store/simulatorAtom'
import { useAxios } from '@/hooks/useAxios'

import { useModuleBasicSetting } from '@/hooks/module/useModuleBasicSetting'
import { isObjectNotEmpty } from '@/util/common-utils'

export default function CanvasMenu(props) {
  const { menuNumber, setMenuNumber } = props
  const pathname = usePathname()
  const router = useRouter()
  const { addPopup } = usePopup()
  const canvasMenus = useRecoilValue(menusState)
  const [type, setType] = useRecoilState(menuTypeState)
  const [verticalHorizontalMode, setVerticalHorizontalMode] = useRecoilState(verticalHorizontalModeState)
  const [appMessageState, setAppMessageState] = useRecoilState(appMessageStore)
  const [currentMenu, setCurrentMenu] = useRecoilState(currentMenuState)
  const setOuterLinePoints = useSetRecoilState(outerLinePointsState)
  const setPlacementPoints = useSetRecoilState(placementShapeDrawingPointsState)
  const canvasSetting = useRecoilValue(canvasSettingState)
  const [canvasZoom, setCanvasZoom] = useRecoilState(canvasZoomState)
  const sessionState = useRecoilValue(sessionStore)
  const globalLocale = useRecoilValue(globalLocaleStore)
  const canvas = useRecoilValue(canvasState)
  const { handleZoomClear, handleZoom } = useCanvasEvent()
  const { handleMenu } = useMenu()

  const { handleEstimateSubmit } = useEstimateController()
  const estimateRecoilState = useRecoilValue(estimateState)
  const [estimatePopupOpen, setEstimatePopupOpen] = useState(false)
  const [estimateCopyPopupOpen, setEstimateCopyPopupOpen] = useState(false)

  const { getMessage } = useMessage()
  const { saveCanvas } = usePlan()
  const { swalFire } = useSwal()
  const { initEvent, addCanvasMouseEventListener, addDocumentEventListener } = useEvent()
  // const { initEvent, addCanvasMouseEventListener, addDocumentEventListener } = useContext(EventContext)
  const commonUtils = useRecoilValue(commonUtilsState)
  const { commonFunctions } = useCommonUtils()
  const SelectOption = [{ name: '瓦53A' }, { name: '瓦53A' }]
  const { floorPlanState, setFloorPlanState } = useContext(FloorPlanContext)
  const { restoreModuleInstArea } = useModuleBasicSetting()

  //견적서버튼 노출용
  const [buttonStyle, setButtonStyle] = useState('')

  const onClickNav = (menu) => {
    setMenuNumber(menu.index)
    setCurrentMenu(menu.title)

    switch (menu.index) {
      case 1:
        setType('placementShape')
        onClickPlacementInitialMenu()
        break
      case 2:
        setType('outline')
        break
      case 3:
        if (type === 'module') {
          restoreModuleInstArea()
        }

        setType('surface')
        break
      case 4:
        setType('module')
        break
      case 6:
        router.push(`/floor-plan/simulator/${menu.index}`)
        break
    }

    if (pathname !== '/floor-plan') router.push('/floor-plan')
  }

  const settingsModalOptions = useRecoilState(settingModalFirstOptionsState)

  useEffect(() => {
    if (menuNumber === 1) {
      onClickPlacementInitialMenu()
    }
  }, [menuNumber, type])

  // 저장버튼(btn08) 클릭 시 호출되는 함수
  const handleSaveCanvas = async () => {
    await saveCanvas()
  }

  const [placementInitialId, setPlacementInitialId] = useState(uuidv4())
  const placementInitialProps = {
    id: placementInitialId,
    pos: {
      x: 50,
      y: 180,
    },
  }
  const onClickPlacementInitialMenu = () => {
    addPopup(placementInitialId, 1, <PlacementShapeSetting {...placementInitialProps} />)
  }

  const handleClear = () => {
    setOuterLinePoints([])
    setPlacementPoints([])
    canvas?.clear()
  }
  //
  // const handleZoomClear = () => {
  //   setCanvasZoom(100)
  //   canvas.set({ zoom: 1 })
  //   canvas.viewportTransform = [1, 0, 0, 1, 0, 0]
  //   canvas.renderAll()
  // }

  const handlePopup = () => {
    const id = uuidv4()
    addPopup(id, 1, <SettingModal01 id={id} />, true)
  }

  // 견적서 초기화 버튼
  const handleEstimateReset = () => {
    // console.log('estimateRecoilState::', estimateRecoilState)
    //objectNo, planNo
    swalFire({
      //저장된 견적서 정보가 초기화되고, 도면정보가 반영됩니다. 정말로 초기화 하시겠습니까?
      //물건정보
      text: getMessage('estimate.detail.reset.confirmMsg'),
      type: 'confirm',
      confirmFn: () => {
        console.log('내용초기화 및 변경일시 갱신')
      },
      denyFn: () => {
        console.log('초기화하지 않음. 변경일시 갱신안함')
      },
    })
  }

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

  useEffect(() => {
    if ([2, 3].some((num) => num === canvasSetting?.roofSizeSet)) {
      setMenuNumber(3)
      setType('surface')
      setCurrentMenu(MENU.BATCH_CANVAS.BATCH_DRAWING)
    } else {
      setMenuNumber(2)
      setType('outline')
      setCurrentMenu(MENU.ROOF_COVERING.EXTERIOR_WALL_LINE)
    }
  }, [canvasSetting])

  const checkMenuState = (menu) => {
    return ([2, 3].some((num) => num === canvasSetting?.roofSizeSet) && menu.index === 2) || (menuNumber === 4 && menu.index === 2)
  }

  // 발전시물레이션 Excel/PDF 다운
  const { promisePost } = useAxios(globalLocale)
  const objectRecoil = useRecoilValue(floorPlanObjectState)
  const pwrGnrSimTypeRecoil = useRecoilValue(pwrGnrSimTypeState)

  const { plans } = usePlan()
  const plan = plans.find((plan) => plan.isCurrent === true)

  const handleExcelPdfFileDown = async (donwloadType, drawingFlg) => {
    const url = '/api/estimate/excel-download'

    const params = {
      objectNo: objectRecoil.floorPlanObjectNo,
      planNo: plan?.id,
      schDownload: donwloadType,
      schDrawingFlg: drawingFlg,
      pwrGnrSimType: pwrGnrSimTypeRecoil.type,
    }

    const options = { responseType: 'blob' }
    await promisePost({ url: url, data: params, option: options })
      .then((resultData) => {
        if (resultData) {
          let fileName = 'unknow'
          const blob = new Blob([resultData.data], { type: resultData.headers['content-type'] || 'application/octet-stream' })
          const fileUrl = window.URL.createObjectURL(blob)

          const link = document.createElement('a')
          link.href = fileUrl

          //서버에서 내려오는 파일명
          const contentDisposition = resultData.headers['content-disposition']
          if (contentDisposition) {
            fileName = contentDisposition.split('filename=')[1].replace(/['"]/g, '')
          }

          link.download = fileName
          document.body.appendChild(link)
          link.click()
          link.remove()
          window.URL.revokeObjectURL(fileUrl)
        }
      })
      .catch((error) => {
        alert('File does not exist.')
      })
  }

  useEffect(() => {
    if (isObjectNotEmpty(estimateRecoilState)) {
      if (estimateRecoilState?.createUser === 'T01') {
        if (sessionState.userId !== 'T01') {
          setButtonStyle('none')
        }
      }
    }
  }, [estimateRecoilState])

  return (
    <div className={`canvas-menu-wrap ${[2, 3, 4].some((num) => num === menuNumber) ? 'active' : ''}`}>
      <div className="canvas-menu-inner">
        <ul className="canvas-menu-list">
          {canvasMenus.map((menu) => {
            return (
              <li
                key={`canvas-menu-${menu.index}`}
                className={`canvas-menu-item ${menuNumber === menu.index ? 'active' : ''}`}
                onClick={() => {
                  if ([2, 3].some((num) => num === canvasSetting?.roofSizeSet) && menu.index === 2) return
                  if (menuNumber === 4 && menu.index === 2) return
                  onClickNav(menu)
                }}
              >
                <button className={checkMenuState(menu) ? 'no-click' : ''}>
                  <span className={`menu-icon ${menu.icon}`}></span>
                  {getMessage(menu.name)}
                </button>
              </li>
            )
          })}
        </ul>
        <div className="canvas-side-btn-wrap">
          {![5, 6].some((num) => num === menuNumber) && (
            <>
              {
                <div className={`vertical-horizontal ${verticalHorizontalMode ? 'on' : ''}`}>
                  <span>{getMessage('plan.mode.vertical.horizontal')}</span>
                  <button onClick={() => setVerticalHorizontalMode(!verticalHorizontalMode)}>{verticalHorizontalMode ? 'ON' : 'OFF'}</button>
                </div>
              }
              <div className="btn-from">
                <button className={`btn01 ${commonUtils.text ? 'active' : ''}`} onClick={() => commonFunctions('text')}></button>
                <button className={`btn02 ${commonUtils.dimension ? 'active' : ''} `} onClick={() => commonFunctions('dimension')}></button>
                <button className={`btn03 ${commonUtils.distance ? 'active' : ''} `} onClick={() => commonFunctions('distance')}></button>
              </div>
              <div className="select-box">
                <QSelectBox title={'瓦53A'} option={SelectOption} />
              </div>
              <div className="btn-from">
                <button
                  className={`btn10 ${floorPlanState.refFileModalOpen && 'active'}`}
                  onClick={() => setFloorPlanState({ ...floorPlanState, refFileModalOpen: true })}
                ></button>
                {/*<button className="btn04" onClick={() => setShowCanvasSettingModal(true)}></button>*/}
                <button className="btn04" onClick={handlePopup}></button>
                <button className="btn05"></button>
                <button className="btn06"></button>
              </div>
              <div className="size-control">
                <button
                  className="control-btn minus"
                  onClick={() => {
                    handleZoom(false)
                  }}
                ></button>
                <span onClick={handleZoomClear}>{canvasZoom}%</span>
                <button
                  className="control-btn plus"
                  onClick={() => {
                    handleZoom(true)
                  }}
                ></button>
              </div>
              <div className="btn-from">
                <button className="btn08" onClick={handleSaveCanvas}></button>
                <button className="btn09"></button>
              </div>
            </>
          )}

          {menuNumber === 5 && (
            <>
              <div className="ico-btn-from">
                <button className="btn-frame gray ico-flx" onClick={() => setEstimatePopupOpen(true)}>
                  <span className="ico ico01"></span>
                  <span className="name">{getMessage('plan.menu.estimate.docDown')}</span>
                </button>
                <button style={{ display: buttonStyle }} className="btn-frame gray ico-flx" onClick={handleEstimateSubmit}>
                  <span className="ico ico02"></span>
                  <span className="name">{getMessage('plan.menu.estimate.save')}</span>
                </button>
                <button
                  style={{ display: buttonStyle }}
                  className="btn-frame gray ico-flx"
                  onClick={() => {
                    handleEstimateReset()
                  }}
                >
                  <span className="ico ico03"></span>
                  <span className="name">{getMessage('plan.menu.estimate.reset')}</span>
                </button>

                {estimateRecoilState?.docNo !== null && (sessionState.storeId === 'T01' || sessionState.storeLvl === '1') && (
                  <button
                    className="btn-frame gray ico-flx"
                    onClick={() => {
                      setEstimateCopyPopupOpen(true)
                    }}
                  >
                    <span className="ico ico04"></span>
                    <span className="name">{getMessage('plan.menu.estimate.copy')}</span>
                  </button>
                )}
                <button style={{ display: buttonStyle }} className="btn-frame gray ico-flx">
                  <span className="ico ico05"></span>
                  <span className="name">{getMessage('plan.menu.estimate.unLock')}</span>
                </button>
              </div>
            </>
          )}
          {menuNumber === 6 && (
            <>
              <div className="ico-btn-from">
                <button type="button" className="btn-frame gray ico-flx" onClick={() => handleExcelPdfFileDown('EXCEL', '2')}>
                  <span className="ico ico01"></span>
                  <span>{getMessage('plan.menu.simulation.excel')}</span>
                </button>
                <button type="button" className="btn-frame gray ico-flx" onClick={() => handleExcelPdfFileDown('PDF', '2')}>
                  <span className="ico ico01"></span>
                  <span>{getMessage('plan.menu.simulation.pdf')}</span>
                </button>
              </div>
            </>
          )}
        </div>
      </div>
      <div className={`canvas-depth2-wrap ${[2, 3, 4].some((num) => num === menuNumber) ? 'active' : ''}`}>
        {[2, 3, 4].some((num) => num === menuNumber) && <MenuDepth01 />}
      </div>
      {/* 견적서(menuNumber=== 5) 상세화면인경우 문서다운로드 팝업 */}
      {estimatePopupOpen && <DocDownOptionPop planNo={estimateRecoilState?.planNo} setEstimatePopupOpen={setEstimatePopupOpen} />}
      {/* 견적서(menuNumber ===5)복사 팝업 */}
      {estimateCopyPopupOpen && <EstimateCopyPop planNo={estimateRecoilState?.planNo} setEstimateCopyPopupOpen={setEstimateCopyPopupOpen} />}
    </div>
  )
}
