import React, {useEffect} from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import hoistNonReactStatics from 'hoist-non-react-statics'
import {updateTitle} from 'store/actions'
import {getTitle} from 'store/selectors'

const connectPage = (Component, mapStateToProps, mapDispatchToProps) => {
    const displayName = Component.displayName || Component.name

    const ConnectedPage = ({pageTitle, ...props}) => {
        useEffect(() => {
            window.scrollTo && window.scrollTo(0, 0)
            props.updateTitle({title: Component.pageTitle})
        }, [])

        useEffect(() => {
            if (typeof pageTitle !== 'string') {
                throw new TypeError(`Expected pageTitle to be of type string.`)
            }

            window.document.title = `${pageTitle} | ES`
        }, [pageTitle])

        return <Component {...props} />
    }

    ConnectedPage.propTypes = {
        ...Component.propTypes,
        pageTitle: PropTypes.string,
        updateTitle: PropTypes.func,
    }

    ConnectedPage.displayName = `connected(${displayName})`

    const selectors = (state, props) => {
        let mappedProps = {}

        if (typeof mapStateToProps === 'function') {
            mappedProps = {...mapStateToProps(state, props)}
        }

        mappedProps = {
            pageTitle: getTitle(state),
            ...mappedProps,
        }

        return mappedProps
    }

    const actionDispatchers = (dispatch) => {
        let dispatchers = {}

        if (typeof mapDispatchToProps === 'function') {
            dispatchers = {...mapDispatchToProps(dispatch)}
        }

        dispatchers = {
            ...dispatchers,
            ...bindActionCreators({updateTitle}, dispatch),
        }

        return dispatchers
    }

    return connect(
        selectors,
        actionDispatchers
    )(hoistNonReactStatics(ConnectedPage, Component))
}

export default connectPage
