import React from 'react'
import PropTypes from 'prop-types'
import investmentApproaches from 'common-fe/constants/investment-approaches'

import Icon from 'react-uikit/icon'

import styles from './styles.scss'
import BEMModule from 'utils/bem'
const bem = new BEMModule(styles)

const PortfolioDescription = ({
    canEdit,
    className,
    description,
    investmentApproach,
    maxLength,
    onOpenPortfolioDescription,
    onOpenPortfolioSettings,
}) => {
    const portfolioApproachDisplay = investmentApproach
        ? investmentApproaches[investmentApproach].label
        : investmentApproaches.NONE.label

    const portfolioDescription = description || 'No description has been added.'

    const descriptionExists = description && description.length > 0
    const isTruncated = descriptionExists && description.length > maxLength
    const truncatedDescription = isTruncated
        ? `${portfolioDescription.slice(0, maxLength - 1)}…`
        : portfolioDescription

    const approachClassNames = bem.classNames(
        'c-portfolio-description__approach'
    )
    const descriptionClassNames = bem.classNames(
        'c-portfolio-description__description',
        {
            isSettings: !descriptionExists,
        }
    )
    const iconClassNames = bem.classNames('c-portfolio-description__icon')

    const handleClick = () => {
        const handler =
            descriptionExists || !canEdit
                ? onOpenPortfolioDescription
                : onOpenPortfolioSettings

        handler && handler()
    }

    return (
        <div className={className}>
            <h3 className={approachClassNames}>{portfolioApproachDisplay}</h3>
            <p className={descriptionClassNames} onClick={handleClick}>
                {descriptionExists || !canEdit ? (
                    truncatedDescription
                ) : (
                    <React.Fragment>
                        <Icon name="edit" className={iconClassNames} />
                        <span>Add description</span>
                    </React.Fragment>
                )}
            </p>
        </div>
    )
}

PortfolioDescription.propTypes = {
    canEdit: PropTypes.bool,
    className: PropTypes.string,
    description: PropTypes.string,
    investmentApproach: PropTypes.string,
    maxLength: PropTypes.number,
    onOpenPortfolioDescription: PropTypes.func,
    onOpenPortfolioSettings: PropTypes.func,
}

PortfolioDescription.defaultProps = {
    maxLength: 145,
}

export default PortfolioDescription
