import {PageContainer, PageContainerProps, View} from "@tarojs/components";
import {CSSProperties, FC, useCallback, useEffect, useState} from "react";
import styles from './custom-page-container.module.scss'
import Taro from "@tarojs/taro";

export const PageContainerInner: FC<PageContainerProps> = (props) => {
  const [visible, setVisible] = useState(props.show)
  const [playing, setPlaying] = useState(false)


  useEffect(() => {
    if (visible !== props) {
      if (props.show) {
        if (playing) {
          setTimeout(() => {
            setVisible(props.show)
          }, 400)
        } else {
          setVisible(props.show)
        }
      } else {
        setPlaying(true)
        setTimeout(() => {
          setPlaying(false)
          setVisible(props.show)
        }, 400)
      }
    }

    if (!props.show) {
      (props.onBeforeLeave as Function)?.();
      (props.onAfterLeave as Function)?.();
    }
  }, [props.show])


  const contentStyle = useCallback((): CSSProperties => {
    let style: CSSProperties = {}

    switch (props.position) {
      case "top":
        style.borderRadius = '0 0 10px 10px'
        style.top = 0
        break
      case 'bottom':
        style.borderRadius = '10px 10px 0 0'
        style.bottom = 0
        break
      case 'center':
        style.width = '90%'
        style.borderRadius = '10px'
        style.padding = '0'
        break
    }

    return style
  }, [])

  const childrenAnimation = useCallback(() => {
    switch (props.position) {
      case "top":
      case 'bottom':
        return props.show ? styles.childrenButton : styles.childrenButtonQuit
      case 'center':
        return props.show ? styles.childrenCenter : styles.childrenCenterQuit
    }
  }, [props.show])

  Taro.useDidHide(() => {
    props.onClickOverlay?.(null as any)
    setVisible(false)
  })

  return (
    <View
      className={styles.customPageContainer}
      style={`${visible ? 'display:flex' : 'display:none'}`}>
      <View
        className={`${styles.overlay} ${props.show ? styles.overlayEnter : styles.overlayQuit}`}
        onClick={props.onClickOverlay}/>
      <View
        className={`${styles.content} ${childrenAnimation()}`}
        style={contentStyle()}>
        {props.children}
      </View>
    </View>
  )
}

const CustomPageContainer: FC<PageContainerProps> = (props) => {
  if (props.position === 'center') {
    return <PageContainerInner {...props} />
  }
  if (process.env.TARO_ENV !== 'h5') {
    return (<PageContainer {...props} round>
      <View className={styles.content} style={{position: 'relative'}}>{props.children}</View>
    </PageContainer>)
  }
  return (<PageContainerInner {...props} />);
}

export default CustomPageContainer
