import React, { memo } from 'react'
import { Flex, Box, css } from 'theme-ui'

export interface MenuTriggerProps {
    active?: boolean
    onChange?: (value: boolean) => void
}

export const MenuTrigger: React.FunctionComponent<MenuTriggerProps> = memo(
    ({ active, onChange }) => {
        const spanStyle = css({
            position: 'absolute',
            height: '2px',
            width: '22px',
            background: 'currentColor',
            borderRadius: '2px',
            transition: 'default',
            willChange: 'transform,opacity'
        })

        function toggle() {
            if (onChange) {
                onChange(!active)
            }
        }

        return (
            <Flex
                sx={{
                    width: '40px',
                    p: 3,
                    height: 'min-content',
                    alignItems: 'center',
                    justifyContent: 'center',
                    position: 'relative',
                    cursor: 'pointer'
                }}
                onClick={toggle}
            >
                <Box
                    css={spanStyle}
                    sx={{
                        transform: `translateY(${active ? 0 : -6}px) rotate(${active ? 45 : 0}deg)}`
                    }}
                />
                <Box
                    css={spanStyle}
                    sx={{
                        transform: `rotate(${active ? -45 : 0}deg)}`
                    }}
                />
                <Box
                    css={spanStyle}
                    sx={{
                        transformOrigin: 'right',
                        transform: `translateY(${active ? 12 : 6}px) scaleX(0.7)}`,
                        opacity: active ? 0 : 1
                    }}
                />
            </Flex>
        )
    }
)

MenuTrigger.defaultProps = {
    active: false
}
