'use client'

import { useContext, useEffect } from 'react'
import { FloorPlanContext } from '@/app/floor-plan/FloorPlanProvider'

import { useMessage } from '@/hooks/useMessage'
import { useRefFiles } from '@/hooks/common/useRefFiles'
import { usePlan } from '@/hooks/usePlan'

import WithDraggable from '@/components/common/draggable/WithDraggable'
import { useCanvas } from '@/hooks/useCanvas'
import { useImgLoader } from '@/hooks/floorPlan/useImgLoader'
// import { initImageLoaderPopup } from '@/lib/planAction'

/**
 * 이미지 로드 모달
 * @returns
 */
export default function ImgLoad() {
  const { currentCanvasPlan, setCurrentCanvasPlan } = usePlan()
  const { getMessage } = useMessage()
  const { canvas } = useCanvas()
  const { floorPlanState, setFloorPlanState } = useContext(FloorPlanContext)
  const {
    refImage,
    queryRef,
    setRefImage,
    handleRefFile,
    refFileMethod,
    setRefFileMethod,
    handleRefFileMethod,
    mapPositionAddress,
    setMapPositionAddress,
    handleFileDelete,
    handleMapImageDown,
    handleAddressDelete,
  } = useRefFiles()
  const { handleCanvasToPng } = useImgLoader()

  const handleModal = () => {
    setFloorPlanState({ ...floorPlanState, refFileModalOpen: false, toggleRotate: false })
    // setCurrentCanvasPlan({
    //   ...currentCanvasPlan,
    //   bgImageName: refImage?.name ?? null,
    //   mapPositionAddress,
    // })
  }

  useEffect(() => {
    console.log('🚀 ~ ImgLoad ~ floorPlanState.refFileModalOpen:', floorPlanState.refFileModalOpen)
    console.log('🚀 ~ ImgLoad ~ currentCanvasPlan:', currentCanvasPlan)
    if (floorPlanState.refFileModalOpen) {
      // initImageLoaderPopup({ objectNo: currentCanvasPlan.objectNo, planNo: currentCanvasPlan.planNo })
    }
  }, [floorPlanState.refFileModalOpen])

  useEffect(() => {
    const backGroundImage = canvas?.getObjects().filter((obj) => obj.name === 'backGroundImage')
    if (backGroundImage && backGroundImage.length === 1) {
      backGroundImage[0].set({
        lockMovementX: !floorPlanState.toggleRotate,
        lockMovementY: !floorPlanState.toggleRotate,
        lockRotation: !floorPlanState.toggleRotate,
        lockScalingX: !floorPlanState.toggleRotate,
        lockScalingY: !floorPlanState.toggleRotate,
        selectable: floorPlanState.toggleRotate,
      })
    }
  }, [floorPlanState.toggleRotate])

  useEffect(() => {
    if (!currentCanvasPlan) return
    const refFileMethod = currentCanvasPlan?.mapPositionAddress === null || currentCanvasPlan?.mapPositionAddress?.trim() === '' ? '1' : '2'
    setRefFileMethod(refFileMethod)
    setMapPositionAddress(currentCanvasPlan?.mapPositionAddress ?? '')
  }, [currentCanvasPlan])

  return (
    <WithDraggable isShow={floorPlanState.refFileModalOpen} pos={{ x: 1000, y: 200 }} className="r">
      <WithDraggable.Header
        title={getMessage('common.input.file')}
        onClose={() => setFloorPlanState({ ...floorPlanState, refFileModalOpen: false })}
      />

      <WithDraggable.Body>
        <div className="img-flex-box">
          <span className="normal-font mr10">{getMessage('modal.image.load.size.rotate')}</span>
          <label className="toggle-btn">
            <input
              type="checkbox"
              checked={floorPlanState.toggleRotate}
              onChange={(e) => setFloorPlanState({ ...floorPlanState, toggleRotate: e.target.checked })}
            />
            <span className="slider"></span>
          </label>
        </div>
        <div className="img-load-from">
          <div className="img-load-item">
            <div className="d-check-radio pop">
              <input type="radio" name="radio03" id="ra06" value={'1'} onChange={(e) => handleRefFileMethod(e)} checked={refFileMethod === '1'} />
              <label htmlFor="ra06">{getMessage('common.input.file')}</label>
            </div>
            <div className="img-flex-box">
              <div className="img-edit-wrap">
                <label className="img-edit-btn" htmlFor="img_file">
                  <span className="img-edit"></span>
                  {getMessage('common.load')}
                </label>
                <input
                  type="file"
                  id="img_file"
                  style={{ display: 'none' }}
                  onChange={refFileMethod === '1' ? (e) => handleRefFile(e.target.files[0]) : () => {}}
                />
              </div>
              <div className="img-name-wrap">
                <input
                  type="text"
                  className="input-origin al-l"
                  value={refImage ? (refImage?.name ?? '') : (currentCanvasPlan?.bgImageName ?? '')}
                  readOnly
                />
                {currentCanvasPlan?.bgImageName && <button className="img-check" onClick={handleFileDelete}></button>}
              </div>
            </div>
          </div>
          <div className="img-load-item">
            <div className="d-check-radio pop">
              <input type="radio" name="radio03" id="ra07" value={'2'} onChange={(e) => handleRefFileMethod(e)} checked={refFileMethod === '2'} />
              <label htmlFor="ra07">{getMessage('common.input.address.load')}</label>
            </div>
            <div className="img-flex-box for-address">
              <input
                type="text"
                ref={queryRef}
                className="input-origin al-l mr10"
                placeholder={'住所入力'}
                value={mapPositionAddress}
                onChange={(e) => setMapPositionAddress(e.target.value)}
              />
              <div className="img-edit-wrap">
                <button
                  className={`img-edit-btn ${mapPositionAddress.trim().length === 0 ? 'no-click' : ''}`}
                  onClick={refFileMethod === '2' ? handleMapImageDown : () => {}}
                >
                  {getMessage('common.finish')}
                </button>
              </div>
              {mapPositionAddress && <button className="check-address fail" onClick={handleAddressDelete}></button>}
              {/* <span className="check-address success"></span> */}
            </div>
          </div>
        </div>
        <div className="grid-btn-wrap">
          <button className="btn-frame modal act" onClick={handleModal}>
            {getMessage('common.finish')}
          </button>
          {/* <button className="btn-frame modal act" onClick={() => handleCanvasToPng(2)}></button> */}
        </div>
      </WithDraggable.Body>
    </WithDraggable>
  )
}
