import { RootPortal, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import classnames from 'classnames'
import type { ReactNode } from 'react'
import { memo, useEffect, useMemo, useRef, useState } from 'react'
import style from './index.module.scss'
import CloseBtnIcon from '@/components/closeBtn'

export interface PopupEvent {
  onClose?: () => void // 关闭事件
  animationEnd?: () => void // 弹出动画结束
}

export interface Params extends PopupEvent {
  title?: string // 标题
  show?: boolean // 显示显示弹窗
  showTitle?: boolean // 是否显示标题
  isFixed?: boolean // 二次弹窗触发
  children?: ReactNode // 插槽内容
  // IconButton?: ReactNode, //
  showIconButton?: boolean // 是否显示关闭按钮
  position?: 'bottom' | 'top' | 'right' // 弹出位置
  customStyle?: React.CSSProperties
  overlayStyle?: React.CSSProperties
  safeAreaInsetBottom?: boolean // 是否为iphoneX提供小黑条适配
  showOverLay?: boolean // 是否显示遮罩层
}
const Popup = ({
  title = '标题',
  show = false,
  showTitle = true,
  onClose,
  isFixed = false,
  showIconButton = false,
  children,
  position = 'bottom',
  animationEnd,
  customStyle = {},
  safeAreaInsetBottom = true,
  showOverLay = true,
  overlayStyle,
}: Params) => {
  const animationTime = useRef<any>(null)
  useEffect(() => {
    if (show) {
      animationTime.current = setTimeout(() => {
        animationEnd?.()
        customStyle.overflow = 'unset'
      }, 260)
    }
    else {
      clearTimeout(animationTime.current)
    }
  }, [show])

  useEffect(() => {
    return () => {
      clearTimeout(animationTime.current)
    }
  }, [])

  return (
    <View className={style.drawer_main}>
      <View catchMove className={classnames(style.drawer, show ? style.drawer_active : '')} style={customStyle}>
        {/* 遮罩层 start */}
        <View
          className={classnames(style.drawer_mask, { [style.drawer_mask_active]: show, [style['drawer_mask--hidden']]: !showOverLay })}
          onClick={onClose}
          style={overlayStyle}
        ></View>
        {/* 遮罩层 end */}
        <View
          style={{ position: `${isFixed == true ? 'fixed' : 'absolute'}` }}
          className={classnames(style.drawer_container, style[`drawer_container_${position}`], {
            [style.drawer_container_active]: show,
            [style[`drawer_container_${position}-withShadow`]]: !showOverLay,
          })}
          onClick={e => e.stopPropagation()}
        >
          {showTitle && <View className={style.drawer_container_title}>{title}</View>}
          {showIconButton && (
            <View className={style.common_close_btn_icon}>
              <CloseBtnIcon onClose={onClose} />
            </View>
          )}

          <View id="drawerContainerContext" className={style.drawer_container_context}>
            {children}
          </View>
          {safeAreaInsetBottom && <View className="common_safe_area_y"></View>}
        </View>
      </View>
    </View>
  )
}

export default memo(Popup)
