'use client'

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

import { usePathname, useRouter, useSearchParams } from 'next/navigation'

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

import { v4 as uuidv4 } from 'uuid'

import MenuDepth01 from './MenuDepth01'
import QSelectBox from '@/components/common/select/QSelectBox'
import SettingModal01 from '@/components/floor-plan/modal/setting01/SettingModal01'
import PlacementShapeSetting from '@/components/floor-plan/modal/placementShape/PlacementShapeSetting'
import EstimateCopyPop from '../estimate/popup/EstimateCopyPop'
import DocDownOptionPop from '../estimate/popup/DocDownOptionPop'
import { FloorPlanContext } from '@/app/floor-plan/FloorPlanProvider'
import { useMessage } from '@/hooks/useMessage'
import { usePlan } from '@/hooks/usePlan'
import { useSwal } from '@/hooks/useSwal'
import { useEvent } from '@/hooks/useEvent'
import { usePopup } from '@/hooks/usePopup'
import { useCanvasEvent } from '@/hooks/useCanvasEvent'
import { useCommonUtils } from '@/hooks/common/useCommonUtils'
import useMenu from '@/hooks/common/useMenu'
import { useEstimateController } from '@/hooks/floorPlan/estimate/useEstimateController'
import { useAxios } from '@/hooks/useAxios'
import { useModuleBasicSetting } from '@/hooks/module/useModuleBasicSetting'
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 { addedRoofsState, basicSettingState, selectedRoofMaterialSelector, settingModalFirstOptionsState } from '@/store/settingAtom'
import { placementShapeDrawingPointsState } from '@/store/placementShapeDrawingAtom'
import { commonUtilsState } from '@/store/commonUtilsAtom'
import { menusState, menuTypeState } from '@/store/menuAtom'
import { estimateState, floorPlanObjectState } from '@/store/floorPlanObjectAtom'
import { pwrGnrSimTypeState } from '@/store/simulatorAtom'
import { isObjectNotEmpty } from '@/util/common-utils'

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

import { MENU } from '@/common/common'

import { QcastContext } from '@/app/QcastProvider'

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 setAppMessageState = useSetRecoilState(appMessageStore)
  const setCurrentMenu = useSetRecoilState(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 urlParams = useSearchParams()
  const { handleEstimateSubmit, fetchSetting } = 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 { floorPlanState, setFloorPlanState } = useContext(FloorPlanContext)

  const [addedRoofs, setAddedRoofsState] = useRecoilState(addedRoofsState)
  const [basicSetting, setBasicSetting] = useRecoilState(basicSettingState)
  const selectedRoofMaterial = useRecoilValue(selectedRoofMaterialSelector)

  //견적서버튼 노출용
  const [buttonStyle1, setButtonStyle1] = useState('') //문서 다운로드 버튼
  const [buttonStyle2, setButtonStyle2] = useState('') //저장 버튼
  const [buttonStyle3, setButtonStyle3] = useState('') //초기화 버튼
  const [buttonStyle4, setButtonStyle4] = useState('') //견적서 복사 버튼
  const [buttonStyle5, setButtonStyle5] = useState('') //잠금 버튼

  const setFloorPlanObjectNo = useSetRecoilState(floorPlanObjectState) //견적서 화면용 물건번호리코일

  // 발전시뮬레이션 메뉴 이동
  const { objectNo, pid } = floorPlanState

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

  const { setIsGlobalLoading } = useContext(QcastContext)

  //임시
  const { selectedPlan } = usePlan()
  const handleExcelPdfFileDown = async (donwloadType, drawingFlg) => {
    const url = '/api/estimate/excel-download'

    const params = {
      objectNo: objectNo,
      planNo: pid,
      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.')
      })
  }

  const onClickNav = (menu) => {
    switch (menu.index) {
      case 0:
        swalFire({
          text: getMessage('stuff.detail.move.confirmMsg'),
          type: 'confirm',
          confirmFn: () => {
            router.push(`/management/stuff/detail?objectNo=${objectNo}`, { scroll: false })
          },
        })
        break
      case 1:
        setType('placementShape')
        onClickPlacementInitialMenu()

        break
      case 2:
        setType('outline')
        break
      case 3:
        setType('surface')
        break
      case 4:
        setType('module')
        break
      case 5:
        // let pid = urlParams.get('pid')
        promiseGet({ url: `/api/estimate/${objectNo}/${selectedPlan.ordering}/detail` }).then((res) => {
          if (res.status === 200) {
            const estimateDetail = res.data
            if (estimateDetail.tempFlg === '0' && estimateDetail.estimateDate !== null) {
              setMenuNumber(menu.index)
              setCurrentMenu(menu.title)
              setFloorPlanObjectNo({ floorPlanObjectNo: objectNo })
              router.push(`/floor-plan/estimate/${menu.index}?pid=${selectedPlan.ordering}&objectNo=${objectNo}`)
            } else {
              swalFire({ text: getMessage('estimate.menu.move.valid1') })
            }
          }
        })
        break
      case 6:
        promiseGet({ url: `/api/estimate/${objectNo}/${selectedPlan.ordering}/detail` }).then((res) => {
          if (res.status === 200) {
            const estimateDetail = res.data
            if (estimateDetail.tempFlg === '0') {
              setMenuNumber(menu.index)
              setCurrentMenu(menu.title)
              router.push(`/floor-plan/simulator/${menu.index}?pid=${selectedPlan.ordering}&objectNo=${objectNo}`)
            } else {
              swalFire({ text: getMessage('simulator.menu.move.valid1') })
            }
          }
        })
        break
    }

    if (menu.index !== 6 && menu.index !== 0 && menu.index !== 5) {
      setMenuNumber(menu.index)
      setCurrentMenu(menu.title)
    }

    if (pathname !== '/floor-plan') {
      if (menu.index !== 0) {
        router.push(`/floor-plan?pid=${pid}&objectNo=${objectNo}`)
      }
    }
  }

  const changeSelectedRoofMaterial = (e) => {
    setBasicSetting({ ...basicSetting, selectedRoofMaterial: e })

    const newAddedRoofs = addedRoofs.map((roof) => {
      if (roof.index === e.index) {
        return { ...roof, selected: true }
      } else {
        return { ...roof, selected: false }
      }
    })

    setAddedRoofsState(newAddedRoofs)
  }

  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 = () => {
    swalFire({
      text: getMessage('estimate.detail.reset.confirmMsg'),
      type: 'confirm',
      confirmFn: async () => {
        setIsGlobalLoading(true)
        const params = {
          objectNo: objectNo,
          planNo: pid,
          userId: sessionState.userId,
        }
        try {
          await promisePost({ url: '/api/estimate/reset-estimate', data: params }).then((res) => {
            if (res.status === 201) {
              swalFire({ text: getMessage('estimate.detail.reset.alertMsg'), type: 'alert' })
              fetchSetting(objectNo, pid, 'R')
            }
          })
        } catch (error) {
          setIsGlobalLoading(false)
          console.log('error::::::::::::', e.response.data.message)
        }
      },
      denyFn: () => {
        setIsGlobalLoading(false)
      },
    })
  }

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

  /*useEffect(() => {
    if (menuNumber === 1) {
      return
    }
    setMenuNumber(1)
    // 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)
    // }
  }, [basicSetting])*/

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

  useEffect(() => {
    if (isObjectNotEmpty(estimateRecoilState)) {
      if (estimateRecoilState?.createUser === 'T01') {
        if (sessionState.userId !== 'T01') {
          setButtonStyle1('none')
          setButtonStyle2('none')
          setButtonStyle3('none')
          setButtonStyle4('none')
          setButtonStyle5('none')
        }
      } else {
        if (estimateRecoilState?.tempFlg === '1') {
          setButtonStyle1('none')
          setButtonStyle2('')
          setButtonStyle3('none')
          setButtonStyle4('none')
          setButtonStyle5('none')
        } else {
          if (estimateRecoilState?.tempFlg === '0' && estimateRecoilState?.lockFlg === '0') {
            setButtonStyle1('')
            setButtonStyle2('')
            setButtonStyle3('')
            setButtonStyle4('')
            setButtonStyle5('')
          } else {
            setButtonStyle1('')
            setButtonStyle2('none')
            setButtonStyle3('none')
            setButtonStyle4('')
            setButtonStyle5('')
          }
        }
      }
    }
  }, [estimateRecoilState])

  /**
   * 견적서 잠금 / 해제
   * lockFlg : 0 잠금해제상태 / 1 잠금상태
   * --보낼때--
   * 0잠금해제는 1잠금으로
   * 1잠금 문서는 0 잠금해제로
   */
  const handleEstimateLockController = (estimateRecoilState) => {
    swalFire({
      // text: estimateRecoilState.lockFlg === '0' ? getMessage('estimate.detail.lock.alertMsg') : getMessage('estimate.detail.unlock.alertMsg'),
      html: estimateRecoilState.lockFlg === '0' ? getMessage('estimate.detail.lock.alertMsg') : getMessage('estimate.detail.unlock.alertMsg'),
      confirmButtonText: estimateRecoilState.lockFlg === '1' ? getMessage('estimate.detail.unlock.confirmBtnName') : '',
      type: 'confirm',
      confirmFn: async () => {
        setIsGlobalLoading(true)
        const params = {
          objectNo: estimateRecoilState.objectNo,
          planNo: estimateRecoilState.planNo,
          lockFlg: estimateRecoilState.lockFlg === '0' ? '1' : '0',
          userId: sessionState.userId,
        }
        try {
          await promisePost({ url: '/api/estimate/save-estimate-lock', data: params }).then((res) => {
            if (res.status === 201) {
              estimateRecoilState.lockFlg = estimateRecoilState.lockFlg === '0' ? '1' : '0'
              if (estimateRecoilState?.createUser === 'T01') {
                if (sessionState.userId !== 'T01') {
                  setButtonStyle1('none')
                  setButtonStyle2('none')
                  setButtonStyle3('none')
                  setButtonStyle4('none')
                  setButtonStyle5('none')
                }
              } else {
                if (estimateRecoilState?.tempFlg === '1') {
                  setButtonStyle1('none')
                  setButtonStyle2('')
                  setButtonStyle3('none')
                  setButtonStyle4('none')
                  setButtonStyle5('none')
                } else {
                  if (estimateRecoilState?.tempFlg === '0' && estimateRecoilState?.lockFlg === '0') {
                    setButtonStyle1('')
                    setButtonStyle2('')
                    setButtonStyle3('')
                    setButtonStyle4('')
                    setButtonStyle5('')
                  } else {
                    setButtonStyle1('')
                    setButtonStyle2('none')
                    setButtonStyle3('none')
                    setButtonStyle4('')
                    setButtonStyle5('')
                  }
                }
              }
            }
            setIsGlobalLoading(false)
          })
        } catch (error) {
          setIsGlobalLoading(false)
          console.log('error::::::::::::', e.response.data.message)
        }
      },
    })
  }

  // 문서다운로드 팝업에서 다운로드 하면 문서 잠금
  const docDownPopLockFlg = () => {
    setButtonStyle1('')
    setButtonStyle2('none')
    setButtonStyle3('none')
    setButtonStyle4('')
    setButtonStyle5('')
  }

  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'].includes(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>
              {isObjectNotEmpty(selectedRoofMaterial) && addedRoofs.length > 0 && (
                <div className="select-box">
                  {
                    <QSelectBox
                      showKey={'roofMatlNm'}
                      options={addedRoofs}
                      value={selectedRoofMaterial}
                      onChange={changeSelectedRoofMaterial}
                      sourceKey={'index'}
                      targetKey={'index'}
                    />
                  }
                </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)}> */}
                <button type="button" style={{ display: buttonStyle1 }} 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 type="button" style={{ display: buttonStyle2 }} className="btn-frame gray ico-flx" onClick={handleEstimateSubmit}>
                  {/* <button type="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
                  type="button"
                  style={{ display: buttonStyle3 }}
                  // 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
                    type="button"
                    style={{ display: buttonStyle4 }}
                    // style={{ display: buttonStyle }}
                    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
                  type="button"
                  style={{ display: buttonStyle5 }}
                  // style={{ display: buttonStyle }}
                  className="btn-frame gray ico-flx"
                  onClick={() => {
                    //시연준비
                    handleEstimateLockController(estimateRecoilState)
                  }}
                >
                  <span className="ico ico05"></span>
                  <span className="name">
                    {estimateRecoilState?.lockFlg === '1' ? getMessage('plan.menu.estimate.unLock') : getMessage('plan.menu.estimate.lock')}
                  </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} docDownPopLockFlg={docDownPopLockFlg} />
      )}
      {/* 견적서(menuNumber ===5)복사 팝업 */}
      {estimateCopyPopupOpen && <EstimateCopyPop planNo={estimateRecoilState?.planNo} setEstimateCopyPopupOpen={setEstimateCopyPopupOpen} />}
    </div>
  )
}
