import { View } from "@tarojs/components"
import Taro from "@tarojs/taro"
import { FC, ReactNode, useEffect, useState } from "react"
import styles from './MyNavBar.module.less'

type MyNavBarProps = {
    isFixed?: boolean
    isPerch?: boolean
    title?: string
    titleColor?: string
    background?: string
    back?: string
    backFn?: () => void
    capsule?: boolean
    left?: ReactNode
    leftColor?: string
}
const MyNavBar: FC<MyNavBarProps> = (props) => {
    const { isFixed = true, isPerch = true, title, titleColor = 'black', background = '#fff', back = true, backFn, capsule = false, left, leftColor = 'black' } = props
    const goBack = () => {
        if (backFn) {
            backFn()
        } else {
            Taro.navigateBack()
        }
    }

    const [navData, setNavData] = useState({
        height: '',
        paddingRight: '',
        paddingTop: '',
        capsuleW: '',
        capsuleH: '',
        capsuleT: ''
    })
    useEffect(() => {
        const { left, width, height, top } = Taro.getMenuButtonBoundingClientRect()
        Taro.getSystemInfo({
            success: (res) => {
                const { statusBarHeight = 0, windowWidth } = res
                setNavData({
                    height: `${(top - statusBarHeight) * 2 + height + statusBarHeight}px`,
                    paddingRight: `${windowWidth - left}px`,
                    paddingTop: `${statusBarHeight}px`,
                    capsuleW: `${width}px`,
                    capsuleH: `${height}px`,
                    capsuleT: `${top}px`
                })
            }
        })
    }, [])

    return <>
        <View
            className={`${styles.headNav} ${isFixed ? styles.fixed : ''}`}
            style={{
                height: navData.height,
                paddingRight: navData.paddingRight,
                paddingTop: navData.paddingTop,
                background
            }}
        >
            {left ? left : <View className={styles.left}>
                <View className={styles.nav} style={{ width: navData.paddingRight }}>
                    {back && !capsule && <View className={styles.back} style={{ color: `${leftColor || '#000'}` }} onClick={goBack}>
                        ❮
                    </View>}
                    {capsule && <View className={styles.capsule} style={{
                        width: navData.capsuleW,
                        height: navData.capsuleH,
                        borderRadius: `calc(${navData.capsuleH} / 2)`,
                        top: navData.capsuleT
                    }}></View>}
                </View>
                <View className={`${styles.title} ${styles.center}`} style={{ color: titleColor }}>{title}</View>
            </View>}
            <View className={styles.right} />
        </View>
        {isFixed && isPerch && <View style={{
            width: '100%',
            height: navData.height
        }} />}
    </>
}

export default MyNavBar