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

export interface Params {
  title?: string // 标题
  show?: false|true // 显示显示弹窗
  showTitle?: false|true // 是否显示标题
  onClose?: () => void // 关闭事件
  children?: ReactNode // 插槽内容
  // IconButton?: ReactNode, //
  showIconButton?: false|true // 是否显示关闭按钮
  position?: 'bottom'|'top'|'right' // 弹出位置
  animationEnd?: () => void // 弹出动画结束
}
export default memo((
  {
    title = '标题',
    show = false,
    showTitle = true,
    onClose,
    showIconButton = false,
    children,
    position = 'bottom',
    animationEnd,
  }: Params) => {
  const animationTime = useRef<any>(null)
  useEffect(() => {
    if (show) {
      animationTime.current = setTimeout(() => {
        animationEnd?.()
      }, 260)
    }
    else {
      clearTimeout(animationTime.current)
    }
  }, [show])

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

  return (
    <>
      <View className={style.drawer_main}>
        <View catchMove className={`${style.drawer} ${show ? style.drawer_active : ''}`}>
          <View
            className={classnames(style.drawer_mask, { [style.drawer_mask_active]: show })}
            onClick={() => onClose?.()}
          >
            <View
              className={classnames(style.drawer_container, style[`drawer_container_${position}`], { [style.drawer_container_active]: show })}
              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 className={style.drawer_container_context}>
                {show && children}
              </View>
              <View className="common_safe_area_y"></View>
            </View>
          </View>
        </View>
      </View>
    </>
  )
})
