import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import {isIOS} from 'common-fe/utils/browser'

class ScrollLock extends React.PureComponent {
    state = {style: {}, scrollPositionY: window.scrollY}

    container = React.createRef()

    componentDidMount() {
        this.isLocked && this.lock()
    }

    componentDidUpdate(prevProps) {
        if (prevProps.isLocked && !this.isLocked) {
            this.unlock()
        } else if (!prevProps.isLocked && this.isLocked) {
            this.lock()
        }
    }

    get isLocked() {
        return this.props.isLocked
    }

    lock = () => {
        const scrollPositionY = window.scrollY

        const lockStyles = {
            position: 'fixed',
            top: `${scrollPositionY * -1}px`,
        }

        if (isIOS()) {
            // We need to apply this fix on mobile safari
            this.container.current.scrollTop = scrollPositionY
        }

        this.setState({
            scrollPositionY,
            style: lockStyles,
        })
        this.props.onLock && this.props.onLock()
    }

    unlock = () => {
        this.setState({style: {}}, () => {
            window.scrollTo && window.scrollTo(0, this.state.scrollPositionY)
        })
        this.props.onUnlock && this.props.onUnlock()
    }

    render() {
        const {style} = this.state

        const {children, className, isLocked} = this.props

        const classes = classNames('c-scroll-lock u-full-width', className, {
            'c-scroll--lock': isLocked,
        })

        return (
            <div className={classes} style={style} ref={this.container}>
                {children}
            </div>
        )
    }
}

ScrollLock.propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    isLocked: PropTypes.bool,
    onLock: PropTypes.func,
    onUnlock: PropTypes.func,
}

export default ScrollLock
