'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 { useRecoilValue } from 'recoil'
import { canvasState } from '@/store/canvasAtom'

export default function ImgLoad() {
  const {
    refImage,
    queryRef,
    setRefImage,
    handleRefFile,
    refFileMethod,
    setRefFileMethod,
    handleRefFileMethod,
    mapPositionAddress,
    setMapPositionAddress,
    handleFileDelete,
    handleMapImageDown,
    handleAddressDelete,
  } = useRefFiles()
  const { currentCanvasPlan, setCurrentCanvasPlan } = usePlan()
  const { getMessage } = useMessage()
  const canvas = useRecoilValue(canvasState)
  const { floorPlanState, setFloorPlanState } = useContext(FloorPlanContext)

  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)
  }, [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 }} handle=".modal">
      <div className={`modal-pop-wrap r`}>
        <div className="modal-head">
          <h1 className="title">{getMessage('common.input.file')}</h1>
          {/* <button className="modal-close">닫기</button> */}
        </div>
        <div className="modal-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
                  />
                  {refImage && <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>
          </div>
        </div>
      </div>
    </WithDraggable>
  )
}
