'use client'
import { useMessage } from '@/hooks/useMessage'
import WithDraggable from '@/components/common/draggable/WithDraggable'
import { useEffect, useRef, useState } from 'react'
import Image from 'next/image'
import PlacementSurface from '@/components/floor-plan/modal/placementSurface/PlacementSurface'
import { useSurfaceShapeBatch } from '@/hooks/surface/useSurfaceShapeBatch'
import { useRecoilValue } from 'recoil'
import { canvasState } from '@/store/canvasAtom'
import { POLYGON_TYPE } from '@/common/common'
import { usePopup } from '@/hooks/usePopup'

export default function PlacementSurfaceSetting({ id, pos = { x: 50, y: 230 } }) {
  const { getMessage } = useMessage()
  const [selectedType, setSelectedType] = useState()
  const [rotate, setRotate] = useState(0)
  const [xInversion, setXInversion] = useState(false)
  const [yInversion, setYInversion] = useState(false)
  const canvas = useRecoilValue(canvasState)
  const { closePopup } = usePopup()
  const [isHidden, setIsHidden] = useState(false)

  const { applySurfaceShape } = useSurfaceShapeBatch({ isHidden, setIsHidden })

  const surfaceShapePolygons = canvas?.getObjects().filter((obj) => obj.name === POLYGON_TYPE.ROOF)

  //오브젝트 배치에서 넘어오면 면형상 선택 가능
  useEffect(() => {
    surfaceShapePolygons.forEach((obj) => {
      obj.set({ selectable: true })
    })
  }, [])

  const surfaceRefs = {
    length1: useRef(null),
    length2: useRef(null),
    length3: useRef(null),
    length4: useRef(null),
    length5: useRef(null),
    lengthetc: useRef(null),
    azimuth: useRef('down'),
  }

  /* type
   * a: line 2
   * b: line 2 + diagonal 1
   * c: line 3
   * d: line 4
   * e: line 5
   * */
  const types = [
    {
      id: 1,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        {
          isDiagonal: true,
          value: 0,
        },
      ],
      info: getMessage('modal.placement.surface.setting.info'),
    },
    {
      id: 2,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 3,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 4,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 5,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 6,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
      lineAmount: 3,
    },
    {
      id: 7,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 8,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 9,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 10,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 11,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 12,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 13,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 14,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 15,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 16,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 17,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
    {
      id: 18,
      lines: [
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
        { isDiagonal: false, value: 0 },
      ],
    },
  ]
  const placementSurfaceProps = {
    ...selectedType,
    rotate,
    xInversion,
    yInversion,
  }

  const getInversionState = () => {
    return `${getScale()} ${getRotate()}`
  }

  const getScale = () => {
    return `scale(${xInversion !== yInversion ? -1 : 1}, 1)`
  }

  const getRotate = () => {
    return `rotate(${90 * rotate}deg)`
  }

  const applySurfaces = () => {
    surfaceRefs.xInversion = xInversion //좌우반전
    surfaceRefs.yInversion = yInversion //상하반전
    surfaceRefs.rotate = rotate * 90 //앵글
    setIsHidden(true)
    applySurfaceShape(surfaceRefs, selectedType, id)
  }

  const handleInversion = (type) => {
    if (type === 'x') {
      const x = xInversion
      setXInversion(!xInversion)
      setRotate(x ? rotate + 2 : rotate - 2)
      // setXInversion(!xInversion)
    } else if (type === 'y') {
      // setRotate(rotate + 2)
      setYInversion(!yInversion)
    }
  }

  useEffect(() => {
    setSelectedType(types[0])
  }, [])

  return (
    <WithDraggable isShow={true} pos={pos} className="lr-2" isHidden={isHidden}>
      <WithDraggable.Header title={getMessage('plan.menu.placement.surface.arrangement')} onClose={() => closePopup(id)} />
      <WithDraggable.Body>
        <div className="plane-frame-wrap">
          <div className="plane-shape-wrap">
            <div className="plane-shape-menu">
              {types.map((type) => (
                <button key={type.id} className={`shape-menu-box ${selectedType?.id === type.id ? 'act' : ''}`} onClick={() => setSelectedType(type)}>
                  <div className="shape-box">
                    <Image
                      src={`/static/images/canvas/plane_shape0${type?.id}.svg`}
                      alt="react"
                      width={0}
                      height={0}
                      style={{
                        width: 'auto',
                        height: 'auto',
                        transform: getInversionState(),
                      }}
                    />
                  </div>
                </button>
              ))}
            </div>
            <div className="shape-library">
              <button className="library-btn ico01" onClick={() => setRotate((yInversion !== xInversion ? rotate - 1 : rotate + 1) % 4)}></button>
              {/* <button className="library-btn ico01" onClick={() => setRotate((rotate + 1) % 4)}></button> */}
              {/* <button className="library-btn ico02" onClick={() => setYInversion(!yInversion)}></button>
                <button className="library-btn ico03" onClick={() => setXInversion(!xInversion)}></button> */}
              <button className="library-btn ico02" onClick={() => handleInversion('y')}></button>
              <button className="library-btn ico03" onClick={() => handleInversion('x')}></button>
            </div>
          </div>
          <div className="plane-detail-wrap">
            <PlacementSurface {...placementSurfaceProps} ref={surfaceRefs} />
            <div className="plane-shape-btn">
              <button className="btn-frame modal act" onClick={applySurfaces}>
                {getMessage('write')}
              </button>
            </div>
          </div>
        </div>
      </WithDraggable.Body>
    </WithDraggable>
  )
}
