'use client'

import { useState } from 'react'
import Draggable from 'react-draggable'
import PopSpinner from '../spinner/PopSpinner'
import { popSpinnerState } from '@/store/popupAtom'
import { useRecoilState } from 'recoil'

export default function WithDraggable({ isShow, children, pos = { x: 0, y: 0 }, handle = '', className = '', hasFooter = true, isHidden = false }) {
  const [position, setPosition] = useState(pos)
  const [popSpinnerStore, setPopSpinnerStore] = useRecoilState(popSpinnerState)

  const handleOnDrag = (e, data) => {
    e.stopPropagation()
    setPosition({ x: data.x, y: data.y })
  }
  // useEffect(() => {
  //   setPosition({ ...pos })
  // }, [])

  return (
    <>
      {isShow && (
        <Draggable
          position={{ x: position.x, y: position.y }}
          onDrag={(e, data) => handleOnDrag(e, data)}
          handle={handle === '' ? '.modal-handle' : handle}
        >
          <div className={`modal-pop-wrap ${className}`} style={{ visibility: isHidden ? 'hidden' : 'visible' }}>
            {children}
            {hasFooter && <WithDraggableFooter />}
            {popSpinnerStore && <PopSpinner />}
          </div>
        </Draggable>
      )}
    </>
  )
}

function WithDraggableHeader({ title, onClose, children }) {
  return (
    <div className="modal-head modal-handle">
      <h1 className="title">{title}</h1>
      {onClose && (
        <button className="modal-close" onClick={() => onClose()}>
          닫기
        </button>
      )}
    </div>
  )
}

function WithDraggableBody({ children }) {
  return (
    <div className="modal-body">
      <div className="left-bar modal-handle"></div>
      <div className="right-bar modal-handle"></div>
      <>{children}</>
    </div>
  )
}

function WithDraggableFooter() {
  return <div className="modal-foot modal-handle"></div>
}

WithDraggable.Header = WithDraggableHeader
WithDraggable.Body = WithDraggableBody
WithDraggable.Footer = WithDraggableFooter
