import {useEffect, useState, MouseEvent} from "react"
import {assets} from "../../assets"
import {ImageView} from "../../atoms"
import {usePopup} from "../../hooks"
import styles from "./styles.module.sass"

export const Popup = () => {
  const [animate, setAnimate] = useState("")
  const {popup, togglePopup} = usePopup()
  const {children, message, heading, isClosable = true} = popup

  useEffect(() => {
    if (children || message) document.body.style.overflow = "hidden"
    else document.body.style.overflow = "visible"
  }, [children, message])

  const handleContentClick = (e: MouseEvent<HTMLDivElement>) => e.stopPropagation()

  useEffect(() => {
    if (popup) {
      const modalContent = document.querySelector(".modal-content")
      if (modalContent) {
        modalContent.scrollTop = 0
      }
    }
  }, [popup])

  const hideWithAnimation = () => {
    setAnimate("hide-animate")
    setTimeout(() => {
      togglePopup()
      setAnimate("")
    }, 400)
  }

  return children || message ? (
    <section className={`blur flex-center ${styles.popup_container}`}>
      <div className={`${animate} ${styles.modal_content}`} onClick={handleContentClick}>
        {heading && (
          <div className={styles.close_popup} data-heading={!!heading}>
            <h4 className={`${styles.heading} semi-bold`}>{heading}</h4>
          </div>
        )}
        {isClosable && (
          <ImageView
            src={assets.ic_close}
            alt="close"
            onClick={hideWithAnimation}
            wrapperClass={styles.close_icon}
            imgSize={32}
          />
        )}
        {message || children}
      </div>
    </section>
  ) : null
}
