import React, {useEffect} from 'react'
import PropTypes from 'prop-types'
import alertTypes from 'containers/alert-manager/alert-types'
import modalTypes from 'containers/modal-manager/modal-types'
import OnboardFeature from '../base'
import routes from 'global/constants/routes'
import {history} from 'router/history'

const OnboardJoinCourse = ({
    autoStart,
    course,
    courseId,
    getCourse,
    onEnd,
    onStart,
    policy,
    showAlert,
    showModal,
    updateTitle,
}) => {
    const hasError = course?.errors?.length > 0
    const canJoin =
        !policy.isProfessor &&
        policy.isParticipant &&
        !policy.hasMaxPortfolios &&
        !policy.user.courses.includes(courseId)

    // Effect for updating the page title whenever the course has been resolved
    useEffect(() => {
        if (!course.isResolved) {
            updateTitle({title: 'Loading...'})
            return
        }

        updateTitle({title: `Welcome to ${course.name}`})
    }, [course.isResolved])

    // Effect for grabbing the data needed for the onboarding if necessary
    useEffect(() => {
        // Cannot complete onboarding without a valid course.
        if (!canJoin) {
            return
        }

        // If we have everything needed, it wont be necessary to do anything
        if (course.isResolved) {
            return
        }

        getCourse?.({courseId})
    }, [canJoin, courseId, course.isResolved])

    useEffect(() => {
        if (hasError) {
            updateTitle({title: `Welcome to EquitySim's Finance Simulation`})

            showAlert({
                type: alertTypes.ERR_JOIN_COURSE,
                buttonText: 'Go Home',
                canDismiss: false,
                onClick: () => {
                    history.push(routes.HOME)
                },
            })
        }
    }, [hasError])

    if (!canJoin || hasError || !policy.isReady || !course.isResolved) {
        return null
    }

    const startPortfolioCreation = ({onEnd}) => {
        showModal({
            type: modalTypes.MODAL_PORTFOLIO_ONBOARDING,
            canDismiss: false,
            course,
            isOnboarding: true,
            withOverlay: false,
            onDismiss: () => {
                onEnd()
                history.push(routes.PORTFOLIO_HOLDINGS)
            },
        })
    }

    const steps = [startPortfolioCreation]

    return (
        <OnboardFeature
            autoStart={autoStart}
            steps={steps}
            onEnd={onEnd}
            onStart={onStart}
        />
    )
}

OnboardJoinCourse.propTypes = {
    policy: PropTypes.object.isRequired,
    autoStart: PropTypes.bool,
    course: PropTypes.object,
    courseId: PropTypes.string,
    getCourse: PropTypes.func,
    showAlert: PropTypes.func,
    showModal: PropTypes.func,
    updateTitle: PropTypes.func,
    onEnd: PropTypes.func,
    onStart: PropTypes.func,
}

export default React.memo(OnboardJoinCourse)
