import React from 'react'
import PropTypes from 'prop-types'
import BEMModule from 'utils/bem'
import styles from './styles.scss'
import securityTypes from 'common-fe/constants/security-types'

const bem = new BEMModule(styles)

const SearchStockItem = ({item, isSelected, nodeRef, onClick}) => {
    const click = () => {
        // Search autocomplete requires item to have a value prop
        // to complete the search bar when clicked – we will use the
        // stock name as the value.
        onClick && onClick({...item, value: item.name})
    }
    const classes = bem.classNames('c-search-stock-item', {
        clickable: onClick,
        selected: isSelected,
    })

    const tickerClasses = bem.classNames('c-search-stock-item__ticker')
    const labelClasses = bem.classNames('c-search-stock-item__label')
    const exchangeClasses = bem.classNames('c-search-stock-item__exchange')

    return (
        <div className={classes} ref={nodeRef} onClick={click}>
            <span className={tickerClasses}>{item.ticker}</span>
            <span className={labelClasses}>
                {item.name}

                {item.type && (
                    <span className={exchangeClasses}>
                        {` – ${securityTypes[item.type].label}`}
                    </span>
                )}
            </span>
            <span className={exchangeClasses}>{item.exchange}</span>
        </div>
    )
}

SearchStockItem.propTypes = {
    item: PropTypes.shape({
        exchange: PropTypes.string,
        name: PropTypes.string,
        ticker: PropTypes.string,
        type: PropTypes.oneOf(Object.keys(securityTypes)),
    }).isRequired,
    isSelected: PropTypes.bool,
    nodeRef: PropTypes.func,
    onClick: PropTypes.func,
}

export default SearchStockItem
