import React, {useCallback, useEffect, useState} from 'react'
import PropTypes from 'prop-types'
import {isPrivateRoute} from 'utils/route'
import Debug from 'common-fe/utils/debug'

import onboardTemplates from 'containers/onboard'
import {getOnboardType} from './helper'

const OnboardManager = ({location, match, policy}) => {
    const [isOnboarding, setIsOnboarding] = useState(false)
    const [onboardType, setOnboardType] = useState(null)
    const {pathname} = location

    const startOnboarding = useCallback(() => setIsOnboarding(true), [])
    const endOnboarding = useCallback(() => setIsOnboarding(false), [])

    // Effect for determining which onboarding flow we should execute.
    // This will run everytime the location or policy has changed.
    useEffect(() => {
        // If we're in the middle of a walkthrough/onboarding flow, no
        // work is needed here, this allows us to continue our current
        // onboarding flow across different routes if need be.
        if (isOnboarding) {
            return
        }

        // Only have to worry about onboarding on private routes.
        if (!isPrivateRoute(pathname)) {
            return
        }

        // If the user is not authenticated, then there is no need execute
        // onboarding for any feature.
        if (!policy.isReady || !policy.isAuthenticated) {
            return
        }

        const onboardType = getOnboardType({pathname, policy})

        setOnboardType(onboardType)
    }, [pathname, policy])

    const {template: OnboardTemplate, props: onboardProps} =
        onboardTemplates[onboardType] || {}

    if (!OnboardTemplate) {
        onboardType &&
            Debug.warn(
                `WARN: No onboard template found for type ${onboardType}.`
            )
        return null
    }

    return (
        <OnboardTemplate
            {...onboardProps}
            location={location}
            match={match}
            policy={policy}
            onStart={startOnboarding}
            onEnd={endOnboarding}
        />
    )
}

OnboardManager.propTypes = {
    location: PropTypes.shape({
        pathname: PropTypes.string,
    }).isRequired,
    match: PropTypes.object.isRequired,
    policy: PropTypes.object.isRequired,
}

export default React.memo(OnboardManager)
