import React, {useEffect, useState} from 'react'
import PropTypes from 'prop-types'
import {Redirect} from 'react-router-dom'
import Background from 'components/background'
import routes from 'global/constants/routes'
import alertTypes from 'containers/alert-manager/alert-types'
import {history} from 'router/history'

const navigateHome = () => history.push(routes.HOME)

const OnboardJoinCoursePage = ({
    courseId,
    policy,
    showAlert,
    userPortfolios,
}) => {
    const [portfolio, setPortfolio] = useState(null)

    // Check to see if the user has already reached the maximum number of
    // portfolios allowed.
    useEffect(() => {
        if (policy.hasMaxPortfolios) {
            showAlert?.({
                type: alertTypes.ERR_MAX_PORTFOLIOS,
                onDismiss: navigateHome,
            })
        }
    }, [])

    // Check to see if the user already has a portfolio tied to this course
    // only on the mounting of this page.
    useEffect(() => {
        const coursePortfolio = Object.values(userPortfolios).find(
            (portfolio) => portfolio.courseSectionId === courseId
        )

        setPortfolio(coursePortfolio)
    }, [courseId])

    // If the user owns a portfolio tied to the course, we will redirect them to
    // their portfolio classroom page.
    if (portfolio) {
        return (
            <Redirect to={`${routes.COURSE}/${courseId}${routes.OVERVIEW}`} />
        )
    }

    return <Background />
}

OnboardJoinCoursePage.pageTitle = `Welcome to EquitySim's Finance Simulation`

OnboardJoinCoursePage.propTypes = {
    courseId: PropTypes.string,
    policy: PropTypes.object,
    showAlert: PropTypes.func,
    userPortfolios: PropTypes.object,
}

export default OnboardJoinCoursePage
