import React from 'react'
import PropTypes from 'prop-types'
import {PORTFOLIO_PERFORMANCE 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 ric from 'request-idle-callback'
import metricIds from 'global/constants/metric-ids'
import routes from 'global/constants/routes'
import rankingPeriods from 'global/constants/ranking-periods'
import withPortfolioPage from '../portfolio-page'

import Banner from 'components/banner'

import PortfolioBenchmarkComparison from 'components/portfolio-benchmark-comparison'
import PortfolioDiversification from 'components/portfolio-diversification'
import PortfolioOverviewGraph from 'components/portfolio-overview-graph'
import PortfolioPageNav from 'components/portfolio-page-nav'
import PortfolioSection from 'components/portfolio-section'
import PortfolioSharpeRatio from 'components/portfolio-sharpe-ratio'

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

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

    componentDidMount() {
        const {
            getPortfolioSharpeTimeseries,
            getPortfolioTimeseries,
            portfolio: {id: portfolioId} = {},
        } = this.props

        if (!portfolioId) {
            return
        }

        ric.requestIdleCallback(() => {
            const config = {alertOnError: false, overrideLoader: true}

            getPortfolioSharpeTimeseries?.(
                {portfolioId, period: rankingPeriods.ALL_TIME},
                config
            )
            getPortfolioTimeseries?.(
                {portfolioId, timeseriesType: metricIds.MARKET_VALUE},
                config
            )
        })
    }

    componentDidUpdate(prevProps) {
        const {
            getPortfolioTimeseries,
            getRankings,
            metrics,
            portfolio: {id: portfolioId},
        } = this.props

        if (prevProps.portfolio.id !== portfolioId) {
            ric.requestIdleCallback(() => {
                const config = {alertOnError: false, overrideLoader: true}

                getPortfolioTimeseries?.({
                    portfolioId,
                    timeseriesType: metricIds.SHARPE_RATIO,
                    period: rankingPeriods.ALL_TIME,
                })

                getPortfolioTimeseries?.(
                    {portfolioId, timeseriesType: metricIds.MARKET_VALUE},
                    config
                )

                if (!metrics?.sharpe?.allTime?.valueDisplay) {
                    getRankings?.({portfolioId})
                }
            })
        }
    }

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

    // 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 {
            benchmarks,
            dailyChangeTimeseries,
            getBenchmark,
            getPortfolioSharpeTimeseries,
            getPortfolioTimeseries,
            historicalValues,
            metrics,
            portfolio,
            sharpeRatioTimeseries,
            tabs,
            user,
        } = this.props
        const {
            activitiesAllowed,
            holdings: {lastDayExists},
            isCourseEnded,
            isCourseStarted,
            isPublic,
            userIds,
        } = portfolio

        const portfolioTypeDisplay = getPortfolioTypeDisplay({portfolio, user})
        const bannerClassNames = bem.classNames(
            'c-portfolio-performance-page__banner'
        )
        const linkClassNames = bem.classNames(
            'c-portfolio-performance-page__link',
            {
                active: !this.isMaxPortfolios,
            }
        )
        const hrClassNames = bem.classNames('c-portfolio-performance-page__hr')
        const sectionClassNames = bem.classNames(
            'c-portfolio-performance-page__section'
        )

        return (
            <React.Fragment>
                <Layout.Section hasBackground className={sectionClassNames}>
                    <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}
                    />
                    {/* Eslint vs Prettier conflict */}
                    {/* eslint-disable indent */}
                    {this.isClassPortfolio &&
                        !activitiesAllowed &&
                        !isCourseEnded && (
                            <React.Fragment>
                                <Banner info className={bannerClassNames}>
                                    {!isCourseStarted && (
                                        <p>{content.courseHasNotStartedText}</p>
                                    )}
                                    {isCourseStarted && (
                                        <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>
                        )}
                    <PortfolioOverviewGraph
                        lastDayExists={activitiesAllowed || lastDayExists}
                        data={historicalValues}
                    />
                </Layout.Section>
                <Layout.Section hasBackground className={sectionClassNames}>
                    <PortfolioBenchmarkComparison
                        portfolio={portfolio}
                        benchmarks={benchmarks}
                        timeseries={dailyChangeTimeseries}
                        getTimeseries={getPortfolioTimeseries}
                        getBenchmark={getBenchmark}
                    />
                </Layout.Section>
                <Layout.Section hasBackground className={sectionClassNames}>
                    <PortfolioDiversification portfolio={portfolio} />
                </Layout.Section>
                <Layout.Section hasBackground className={sectionClassNames}>
                    <PortfolioSharpeRatio
                        getPortfolioSharpeTimeseries={
                            getPortfolioSharpeTimeseries
                        }
                        portfolio={portfolio}
                        timeseries={sharpeRatioTimeseries}
                    />
                </Layout.Section>
            </React.Fragment>
        )
    }
}

PortfolioPerformancePage.propTypes = {
    benchmarks: PropTypes.object,
    dailyChangeTimeseries: PropTypes.object,
    getBenchmark: PropTypes.func,
    getPortfolio: PropTypes.func,
    getPortfolioSharpeTimeseries: PropTypes.func,
    getPortfolioTimeseries: PropTypes.func,
    getRankings: PropTypes.func,
    historicalValues: PropTypes.object,
    metrics: PropTypes.object,
    policy: PropTypes.object,
    portfolio: PropTypes.shape({
        activitiesAllowed: PropTypes.bool,
        holdings: PropTypes.shape({
            lastDayExists: PropTypes.bool,
        }),
        id: PropTypes.string,
        isCourseEnded: PropTypes.bool,
        isCoursePortfolio: PropTypes.bool,
        isCourseStarted: PropTypes.bool,
        isPublic: PropTypes.bool,
        userIds: PropTypes.arrayOf(PropTypes.string),
    }),
    sharpeRatioTimeseries: PropTypes.object,
    showAlert: PropTypes.func,
    showModal: PropTypes.func,
    tabs: PropTypes.array,
    timeseries: PropTypes.object,
    user: PropTypes.object,
}

export default withPortfolioPage(PortfolioPerformancePage)
