import React from 'react'
import PropTypes from 'prop-types'
import {history} from 'router/history'
import {PORTFOLIO_HOLDINGS as TAB} from 'global/constants/portfolio-tabs'
import alertTypes from 'containers/alert-manager/alert-types'
import content from 'global/constants/content'
import Layout from 'components/layout/'
import modalTypes from 'containers/modal-manager/modal-types'
import metricIds from 'global/constants/metric-ids'
import routes from 'global/constants/routes'
import withPortfolioPage from '../portfolio-page'

import Banner from 'components/banner'
import PortfolioPageNav from 'components/portfolio-page-nav'
import PortfolioHoldingsTable from 'components/portfolio-holdings-table'
import PortfolioSection from 'components/portfolio-section'

import {getPortfolioTypeDisplay} from 'utils/portfolio'
import BEMModule from 'utils/bem'
import styles from './styles.scss'
const bem = new BEMModule(styles)

class PortfolioHoldingsPage extends React.PureComponent {
    static pageTitle = `Portfolio ${TAB.label}`
    static pageRoute = routes.PORTFOLIO_HOLDINGS

    componentDidMount() {
        const {
            location: {pathname: currentPathname},
            portfolio: {id: portfolioId} = {},
        } = this.props

        if (!portfolioId) {
            return
        }

        const pathname = `${routes.PORTFOLIO}/${encodeURIComponent(
            portfolioId
        )}${PortfolioHoldingsPage.pageRoute}`

        if (currentPathname !== pathname) {
            history.replace(pathname)
        }
    }

    // Portfolios ==============================================================
    get isMaxPortfolios() {
        return this.props.policy.hasMaxPortfolios
    }

    exportHoldings = () => {
        this.props.showModal?.({
            type: modalTypes.MODAL_PORTFOLIO_DATA_EXPORTATION,
            portfolioId: this.props.portfolio.id,
        })
    }

    getSharpeTimeseries = (securityId) => {
        const {
            portfolio: {id: portfolioId},
        } = this.props

        this.props.getSecurityTimeseries?.({
            securityId,
            portfolioId,
            timeseriesType: metricIds.SHARPE_RATIO,
        })
    }

    // Modals ==================================================================
    openCurrencyExchange = () => {
        this.props.showModal({type: modalTypes.MODAL_CURRENCY_EXCHANGE})
    }

    openPortfolioDescription = () => {
        this.props.showModal?.({
            type: modalTypes.MODAL_PORTFOLIO_DESCRIPTION,
            portfolio: this.props.portfolio,
            user: this.props.user,
        })
    }

    openPortfolioSettings = () => {
        this.props.showModal?.({
            type: modalTypes.MODAL_PORTFOLIO_SETTINGS,
        })
    }

    openTeamManagement = () => {
        this.props.showModal({
            type: modalTypes.MODAL_TEAM_MANAGEMENT,
        })
    }

    openPortfolioDeleteConfirmation = () => {
        this.props.showAlert({
            type: alertTypes.CONFIRM_PORTFOLIO_DELETE,
            portfolio: this.props.portfolio.id,
        })
    }

    openPortfolioLeaveConfirmation = () => {
        this.props.showAlert({
            type: alertTypes.CONFIRM_PORTFOLIO_LEAVE,
            portfolio: this.props.portfolio.id,
        })
    }

    createPersonalPortfolio = () => {
        !this.isMaxPortfolios &&
            this.props.showModal({
                type: modalTypes.MODAL_PORTFOLIO_CREATION,
                isPersonal: true,
            })
    }

    // Navigation ==============================================================
    get activeTab() {
        const {tabs} = this.props
        return tabs.map((tab) => tab.label).indexOf(TAB.label)
    }

    // TODO: Implement portfolio types to check for portfolio type
    // Classroom Environment ===================================================
    get isClassPortfolio() {
        return this.props.portfolio.isCoursePortfolio
    }

    render() {
        const bannerClassNames = bem.classNames(
            'c-portfolio-holdings-page__banner'
        )
        const holdingsClassNames = bem.classNames(
            'c-portfolio-holdings-page__holdings'
        )
        const linkClassNames = bem.classNames(
            'c-portfolio-holdings-page__link',
            {
                active: !this.isMaxPortfolios,
            }
        )
        const hrClassNames = bem.classNames('c-portfolio-holdings-page__hr')

        const {
            metrics,
            portfolio,
            portfolio: {
                activitiesAllowed,
                holdings,
                isCourseEnded,
                isCourseStarted,
                isPublic,
                userIds,
            },
            securities,
            sharpeTimeseriesCollection,
            showModal,
            tabs,
            user,
        } = this.props

        const portfolioTypeDisplay = getPortfolioTypeDisplay({portfolio, user})
        const {hasHoldings} = holdings

        if (!hasHoldings) {
            return (
                <Layout.Section>
                    <PortfolioPageNav type={portfolioTypeDisplay} tabs={tabs} />
                </Layout.Section>
            )
        }

        return (
            <React.Fragment>
                <Layout.Section hasBackground>
                    <PortfolioPageNav
                        activeTab={this.activeTab}
                        isPublic={isPublic}
                        portfolio={portfolio}
                        showPortfolioDeleteConfirmation={
                            this.openPortfolioDeleteConfirmation
                        }
                        showPortfolioLeaveConfirmation={
                            this.openPortfolioLeaveConfirmation
                        }
                        showPortfolioSettings={this.openPortfolioSettings}
                        showTeamManagement={this.openTeamManagement}
                        tabs={tabs}
                        type={portfolioTypeDisplay}
                        users={userIds}
                    />
                    <PortfolioSection
                        metrics={metrics}
                        portfolio={portfolio}
                        onOpenPortfolioDescription={
                            this.openPortfolioDescription
                        }
                        onOpenPortfolioSettings={this.openPortfolioSettings}
                    />
                    {this.isClassPortfolio && !activitiesAllowed && (
                        <React.Fragment>
                            <Banner info className={bannerClassNames}>
                                {!isCourseStarted && (
                                    <p>{content.courseHasNotStartedText}</p>
                                )}
                                {isCourseEnded && (
                                    <p>{content.courseHasEndedText}</p>
                                )}

                                <p>
                                    {/* eslint-disable-next-line max-len */}
                                    If you want to start trading now, you can{' '}
                                    <button
                                        className={linkClassNames}
                                        style={{
                                            border: 0,
                                            backgroundColor: 'transparent',
                                            padding: 0,
                                        }}
                                        onClick={this.createPersonalPortfolio}
                                    >
                                        {' '}
                                        create your own personal portfolio
                                    </button>{' '}
                                    and begin trading immediately.
                                </p>
                            </Banner>
                            <hr className={hrClassNames} />
                        </React.Fragment>
                    )}
                </Layout.Section>
                <Layout.Section hasBackground className={holdingsClassNames}>
                    <PortfolioHoldingsTable
                        exportData={this.exportHoldings}
                        getSharpeTimeseries={this.getSharpeTimeseries}
                        portfolio={portfolio}
                        securities={securities}
                        sharpeTimeseriesCollection={sharpeTimeseriesCollection}
                        showModal={showModal}
                    />
                </Layout.Section>
            </React.Fragment>
        )
    }
}

PortfolioHoldingsPage.propTypes = {
    benchmark: PropTypes.object,
    exportHoldings: PropTypes.func,
    getBenchmark: PropTypes.func,
    getRankings: PropTypes.func,
    getSecurityTimeseries: PropTypes.func,
    location: PropTypes.shape({
        pathname: PropTypes.string,
    }),
    metrics: PropTypes.object,
    policy: PropTypes.object,
    portfolio: PropTypes.shape({
        activitiesAllowed: PropTypes.bool,
        courseSectionId: PropTypes.string,
        description: PropTypes.string,
        holdings: PropTypes.object,
        id: PropTypes.string,
        isCourseEnded: PropTypes.bool,
        isCoursePortfolio: PropTypes.bool,
        isCourseStarted: PropTypes.bool,
        isPublic: PropTypes.bool,
        name: PropTypes.string,
        userIds: PropTypes.arrayOf(PropTypes.string),
    }),
    securities: PropTypes.object,
    sharpeTimeseriesCollection: PropTypes.object,
    showAlert: PropTypes.func,
    showModal: PropTypes.func,
    tabs: PropTypes.array,
    user: PropTypes.object,
}

export default withPortfolioPage(PortfolioHoldingsPage)
