import { XMarkIcon } from '@heroicons/react/24/outline'
import { AnimatePresence, motion } from 'framer-motion'
import { useEffect } from 'react'
import MobileView from '../../views/MobileView'
import DesktopView from '../../views/DesktopView'
import ReactDOM from 'react-dom'

const transition = { ease: 'linear', duration: 0.2 }

const BottomPopup = ({ children, active = false, title, close, className = '' }) => {
  useEffect(() => {
    if (active) {
      document.querySelector('html, body').classList.add('overflow-hidden')
    } else {
      document.querySelector('html, body').classList.remove('overflow-hidden')
    }
  }, [active])

  return ReactDOM.createPortal(
    <>
      <AnimatePresence>
        {active && (
          <>
            <motion.div
              className='overlay'
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={transition}
              onClick={close}
            />
            <MobileView>
              <motion.div
                initial={{ bottom: '-100%' }}
                animate={{ bottom: 0 }}
                exit={{ bottom: '-100%' }}
                transition={transition}
                className={`fixed left-0 w-full border-t border-gray_r-6 rounded-t-xl z-[60] p-4 pt-0 bg-white max-h-[80vh] overflow-auto ${className}`}
              >
                <div className='flex justify-between py-4'>
                  <div className='font-semibold text-h-sm'>{title}</div>
                  {close && (
                    <button type='button' onClick={close}>
                      <XMarkIcon className='w-5 stroke-2' />
                    </button>
                  )}
                </div>
                {children}
              </motion.div>
            </MobileView>

            <DesktopView>
              <motion.div
                initial={{ bottom: '55%', opacity: 0 }}
                animate={{ bottom: '50%', opacity: 1 }}
                exit={{ bottom: '45%', opacity: 0 }}
                transition={transition}
                className={`fixed left-1/2 -translate-x-1/2 translate-y-1/2 md:w-1/4 lg:w-1/3 border border-gray_r-6 rounded-xl z-[60] p-4 pt-0 bg-white max-h-[80vh] overflow-auto ${className}`}
              >
                <div className='flex justify-between py-4'>
                  <div className='font-semibold text-h-sm'>{title}</div>
                  {close && (
                    <button type='button' onClick={close}>
                      <XMarkIcon className='w-5 stroke-2' />
                    </button>
                  )}
                </div>
                {children}
              </motion.div>
            </DesktopView>
          </>
        )}
      </AnimatePresence>
    </>,
    document.querySelector('body')
  )
}

export default BottomPopup
