import React, {useCallback} from 'react'
import PropTypes from 'prop-types'
import {history} from 'router/history'
import {PERMISSIONS, content} from './content'
import BEMModule from 'utils/bem'
import Button from 'react-uikit/button'
import moment from 'moment'
import routes from 'global/constants/routes'
import styles from './styles.scss'
import userRoles from 'common-fe/constants/user-roles'

const bem = new BEMModule(styles)

const JoinButton = ({
    className,
    data: {currentSeats, endDate, id: courseId, name, paidSeats, professor},
    onClick,
    permittedRoles,
    policy,
    user: {courses: usersCourses, id: userId, roles, portfolios},
}) => {
    const reasonClasses = bem.classNames('c-join-page-button__reason')

    const portfolioIdList = Object.keys(portfolios)

    // Find the matching portfolio id of this course
    const portfolioId = portfolioIdList.find(
        (id) => portfolios[id]?.courseSectionId === courseId
    )
    const permissions = {
        // (1) Checks if user’s role is allowed to join.
        // TODO: Replace with below when professors are allowed to use the simulation.
        // [PERMISSIONS.IS_NOT_ALLOWED]: !(roles.some((role) => permittedRoles.includes(role))),
        [PERMISSIONS.IS_NOT_ALLOWED]: roles.includes(userRoles.PROFESSOR),

        // (2) Checks for the available seats at the course.
        [PERMISSIONS.IS_AT_SEAT_LIMIT]: Boolean(
            paidSeats && currentSeats >= paidSeats
        ),

        // (3) Checks if user has available portfolio slots for a new portfolio.
        [PERMISSIONS.IS_AT_PORTFOLIO_LIMIT]: policy.hasMaxPortfolios,

        // (4) Checks if the course has ended.
        [PERMISSIONS.HAS_ENDED]: moment().isSameOrAfter(endDate),

        // (5) Checks if the user is already participating in the course.
        [PERMISSIONS.HAS_JOINED]: usersCourses.includes(courseId),

        // (6) Checks if the user is the owner of the course.
        [PERMISSIONS.IS_OWNER]: professor.id === userId,
    }
    const labelData = {name, role: roles[0], permittedRoles}
    // TODO: keep some sort of mapping of portfolio ids to course section ids so we can navigate to the correct portfolio
    //       For now just navigating the user to finance.equitysim.com
    // const coursePortfolio = Object.values(portfolios).find((portfolio) => portfolio.courseSectionId === courseId)
    const navigateToDashboard = useCallback(
        () => history.push(`${routes.COURSE}/${courseId}`),
        []
    )
    // const navigateToPortfolio = useCallback(() => coursePortfolio &&
    //     history.push(`${routes.PORTFOLIO}/${coursePortfolio.id}`), [])
    const navigateToPortfolio = useCallback(
        () =>
            history.push(
                `${routes.PORTFOLIO}/${portfolioId}${routes.PORTFOLIO_HOLDINGS}`
            ),
        []
    )

    // (1) If the user is the owner of the course, navigate to their dashboard.
    if (permissions[PERMISSIONS.IS_OWNER]) {
        return (
            <div>
                <Button
                    variant="primary"
                    className={className}
                    onClick={navigateToDashboard}
                >
                    Back to dashboard
                </Button>
                <p>{content[PERMISSIONS.IS_OWNER](labelData)}</p>
            </div>
        )
    }

    // (2) If the user is already a participant of the course, navigate to the
    // the portfolio associated with the course.
    // if (permissions[PERMISSIONS.HAS_JOINED] && coursePortfolio) {
    if (permissions[PERMISSIONS.HAS_JOINED]) {
        return (
            <div>
                <Button
                    variant="primary"
                    className={className}
                    onClick={navigateToPortfolio}
                >
                    {/* Go to {coursePortfolio.name} */}
                    Manage your portfolio
                </Button>
                <p className={reasonClasses}>
                    {content[PERMISSIONS.HAS_JOINED](labelData)}
                </p>
            </div>
        )
    }
    // (…) The rest of the permission checks.
    for (const key in permissions) {
        if (permissions[key]) {
            return (
                <div>
                    <Button variant="primary" disabled className={className}>
                        Can’t join
                    </Button>
                    <p className={reasonClasses}>{content[key](labelData)}</p>
                </div>
            )
        }
    }

    return (
        <Button variant="primary" className={className} onClick={onClick}>
            Join
        </Button>
    )
}

JoinButton.propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    data: PropTypes.object,
    permittedRoles: PropTypes.arrayOf(PropTypes.string),
    policy: PropTypes.object,
    portfolios: PropTypes.object,
    user: PropTypes.object,
    onClick: PropTypes.func,
}

export default JoinButton
