import React, { useState } from 'react'
import { Flex, Box } from 'theme-ui'
import { useScrollSwipe } from '../hooks/use-scroll-swipe'
import { Transition } from 'react-transition-group'

/**
 * 导航栏的高度
 * @example
 * ```jsx
 * <Box sx={{ pt: NAV_HEIGHT }}></Box>
 * ```
 */
export const NAV_HEIGHT = '4rem'

export const Navbar: React.FunctionComponent = (props) => {
    const [visible, setVisible] = useState(true)
    useScrollSwipe((direction) => {
        if (direction === 'down') {
            setVisible(false)
        } else if (direction === 'up') {
            setVisible(true)
        }
    })

    return (
        <Transition in={visible} timeout={330}>
            {(state) => {
                const onEnter = state === 'entering' || state === 'entered'
                return (
                    <Box
                        as="nav"
                        sx={{
                            position: 'fixed',
                            left: 0,
                            right: 0,
                            top: 0,
                            zIndex: 3,
                            transition: 'default',
                            // 添加一个伪元素作为背景色，单独过渡
                            '::after': {
                                position: 'absolute',
                                content: '""',
                                transition: 'inherit',
                                transitionDelay: onEnter ? '0ms' : '100ms',
                                left: 0,
                                right: 0,
                                bottom: 0,
                                top: 0,
                                bg: 'background',
                                backdropFilter: 'blur(3px)',
                                zIndex: -1,
                                opacity: onEnter ? 0.9 : 0,
                                willChange: 'opacity'
                            }
                        }}
                    >
                        <Flex
                            sx={{
                                height: NAV_HEIGHT,
                                px: 4,
                                transition: 'inherit',
                                transitionDelay: onEnter ? '100ms' : '0ms',
                                opacity: onEnter ? 1 : 0.5,
                                transform: `translateY(${onEnter ? 0 : -100}%)`,
                                willChange: 'opacity,transform'
                            }}
                        >
                            {props.children}
                        </Flex>
                    </Box>
                )
            }}
        </Transition>
    )
}

export const NavbarItem: React.FunctionComponent = (props) => {
    return (
        <Flex
            sx={{
                alignItems: 'center'
            }}
        >
            {props.children}
        </Flex>
    )
}
