import WithDraggable from '@/components/common/draggable/WithDraggable'
import { useEffect, useState } from 'react'
import QSelectBox from '@/components/common/select/QSelectBox'
import { useRecoilValue } from 'recoil'
import { contextPopupPositionState } from '@/store/popupAtom'
import { useMessage } from '@/hooks/useMessage'
import { usePopup } from '@/hooks/usePopup'
import { canvasState } from '@/store/canvasAtom'
import { usePolygon } from '@/hooks/usePolygon'
import { useSurfaceShapeBatch } from '@/hooks/surface/useSurfaceShapeBatch'
import { useRoofFn } from '@/hooks/common/useRoofFn'

const FLOW_DIRECTION_TYPE = {
  EIGHT_AZIMUTH: 'eightAzimuth',
  TWENTY_FOUR_AZIMUTH: 'twentyFourAzimuth',
}

export default function FlowDirectionSetting(props) {
  const contextPopupPosition = useRecoilValue(contextPopupPositionState)
  const { id, pos = contextPopupPosition, target } = props
  const canvas = useRecoilValue(canvasState)
  const { getMessage } = useMessage()
  const { setSurfaceShapePattern } = useRoofFn()

  const { changeSurfaceLineType } = useSurfaceShapeBatch({})

  useEffect(() => {
    return () => {
      canvas?.discardActiveObject()
    }
  }, [])

  const [compasDeg, setCompasDeg] = useState(target.surfaceCompass ?? null)
  const [flowDirection, setFlowDirection] = useState(target.direction)
  const { closePopup } = usePopup()

  useEffect(() => {
    let newCompassDeg = 0
    if ([-15, 0, 15].includes(compasDeg)) {
      newCompassDeg = 0
    } else if ([30, 45, 60].includes(compasDeg)) {
      newCompassDeg = 45
    } else if ([75, 90, 105].includes(compasDeg)) {
      newCompassDeg = 90
    } else if ([120, 135, 150].includes(compasDeg)) {
      newCompassDeg = 135
    } else if ([165, 180, -165].includes(compasDeg)) {
      newCompassDeg = 180
    } else if ([-120, -135, -150].includes(compasDeg)) {
      newCompassDeg = -135
    } else if ([-105, -90, -75].includes(compasDeg)) {
      newCompassDeg = -90
    } else if ([-60, -45, -30].includes(compasDeg)) {
      newCompassDeg = -45
    } else {
      newCompassDeg = ''
    }
    const newOrientation = orientations.find((item) => item.value === newCompassDeg)
    setSelectedOrientation(newOrientation)
  }, [compasDeg])

  const orientations = [
    { name: `${getMessage('commons.none')}`, value: '' },
    { name: `${getMessage('commons.south')}`, value: 0 },
    { name: `${getMessage('commons.south')}${getMessage('commons.east')}`, value: 45 },
    { name: `${getMessage('commons.south')}${getMessage('commons.west')}`, value: -45 },
    { name: `${getMessage('commons.east')}`, value: 90 },
    { name: `${getMessage('commons.west')}`, value: -90 },
    { name: `${getMessage('commons.north')}${getMessage('commons.east')}`, value: 135 },
    { name: `${getMessage('commons.north')}${getMessage('commons.west')}`, value: -135 },
    { name: `${getMessage('commons.north')}`, value: 180 },
  ]

  const { drawDirectionArrow } = usePolygon()

  const [type, setType] = useState(target.surfaceCompassType ?? FLOW_DIRECTION_TYPE.EIGHT_AZIMUTH)

  const changeSurfaceFlowDirection = (roof, direction, orientation) => {
    roof.set({
      direction: direction,
      surfaceCompass: orientation,
      surfaceCompassType: type,
    })
    setSurfaceShapePattern(roof, null, null, roof.roofMaterial)
    drawDirectionArrow(roof)
    canvas?.renderAll()
    changeSurfaceLineType(roof)
    closePopup(id)
  }

  const [selectedOrientation, setSelectedOrientation] = useState(
    target.surfaceCompassType !== null && target.surfaceCompassType === FLOW_DIRECTION_TYPE.EIGHT_AZIMUTH
      ? orientations.find((item) => item.value === target.surfaceCompass)
      : orientations[0],
  )

  return (
    <WithDraggable isShow={true} pos={pos} className="ml">
      <WithDraggable.Header title={getMessage('modal.shape.flow.direction.setting')} onClose={() => closePopup(id)} />
      <WithDraggable.Body>
        <div className="drawing-flow-wrap">
          <div className="discrimination-box">
            <div className="discrimination-tit mb15">{getMessage('modal.flow.direction.setting')}</div>
            <div className="guide">{getMessage('modal.flow.direction.setting.info')}</div>
            <div className="object-direction-wrap">
              <div className="plane-direction">
                <span className="top">{getMessage('commons.north')}</span>
                <button className={`plane-btn up ${flowDirection === 'north' ? 'act' : ''}`} onClick={() => setFlowDirection('north')}></button>
                <span className="right">{getMessage('commons.east')}</span>
                <button className={`plane-btn right ${flowDirection === 'east' ? 'act' : ''}`} onClick={() => setFlowDirection('east')}></button>
                <span className="bottom">{getMessage('commons.south')}</span>
                <button className={`plane-btn down ${flowDirection === 'south' ? 'act' : ''}`} onClick={() => setFlowDirection('south')}></button>
                <span className="left">{getMessage('commons.west')}</span>
                <button className={`plane-btn left ${flowDirection === 'west' ? 'act' : ''}`} onClick={() => setFlowDirection('west')}></button>
              </div>
            </div>
          </div>
          <div className="discrimination-box">
            <div className="discrimination-tit mb15">{getMessage('modal.module.basic.setting.orientation.setting')}</div>
            <div className="guide">{getMessage('modal.shape.flow.direction.setting.orientation.setting.info')}</div>
            <div className="mb-box">
              <div className="d-check-radio pop mb15">
                <input
                  type="radio"
                  name="radio01"
                  id="ra01"
                  checked={type === FLOW_DIRECTION_TYPE.EIGHT_AZIMUTH}
                  onChange={(e) => {
                    setCompasDeg(0)
                    setType(FLOW_DIRECTION_TYPE.EIGHT_AZIMUTH)
                  }}
                />
                <label htmlFor="ra01">{getMessage('modal.shape.flow.direction.setting.orientation.8')}</label>
              </div>
              <div className="grid-select ">
                <QSelectBox
                  value={selectedOrientation}
                  options={orientations}
                  onChange={(e) => {
                    if (e.value === '') {
                      setCompasDeg(null)
                      setSelectedOrientation(e)
                      return
                    }
                    setType(FLOW_DIRECTION_TYPE.EIGHT_AZIMUTH)
                    setSelectedOrientation(e)
                    setCompasDeg(e.value)
                  }}
                  showKey={'name'}
                  targetKey={'value'}
                  sourceKey={'value'}
                />
              </div>
            </div>
            <div className="mb-box">
              <div className="d-check-radio pop">
                <input
                  type="radio"
                  name="radio01"
                  id="ra02"
                  value={1}
                  checked={type === FLOW_DIRECTION_TYPE.TWENTY_FOUR_AZIMUTH}
                  onChange={(e) => {
                    setType(FLOW_DIRECTION_TYPE.TWENTY_FOUR_AZIMUTH)
                  }}
                />
                <label htmlFor="ra02">{getMessage('modal.shape.flow.direction.setting.orientation.24')}</label>
              </div>
            </div>
            <div className="draw-flow-wrap">
              <div className="compas-box">
                <div className="compas-box-inner">
                  {Array.from({ length: 180 / 15 }).map((dot, index) => (
                    <div
                      key={index}
                      className={`circle ${compasDeg === -15 * index + 180 ? 'act' : ''}`}
                      onClick={() => {
                        if (index === 0) {
                          setCompasDeg(180)
                          return
                        }
                        setType(FLOW_DIRECTION_TYPE.TWENTY_FOUR_AZIMUTH)
                        setCompasDeg(-15 * index + 180)
                      }}
                    ></div>
                  ))}
                  {Array.from({ length: 180 / 15 }).map((dot, index) => (
                    <div
                      key={index}
                      className={`circle ${compasDeg === -1 * 15 * index ? 'act' : ''}`}
                      onClick={() => {
                        setType(FLOW_DIRECTION_TYPE.TWENTY_FOUR_AZIMUTH)
                        setCompasDeg(15 * index * -1)
                      }}
                    ></div>
                  ))}
                  <div className="compas">
                    <div className="compas-arr" style={{ transform: `${`rotate(${-1 * compasDeg}deg)`}` }}></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className="grid-btn-wrap">
          <button className="btn-frame modal act" onClick={() => changeSurfaceFlowDirection(target, flowDirection, compasDeg)}>
            {getMessage('modal.common.save')}
          </button>
        </div>
      </WithDraggable.Body>
    </WithDraggable>
  )
}
