import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {isFunction} from 'lodash';

import {filterKeyCodes} from '../../utils/functions';
import {Icon} from '../Icon';

export class BreadCrumb extends PureComponent {
    static propTypes = {
        id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
        name: PropTypes.string.isRequired,
        index: PropTypes.number.isRequired,
        isFirst: PropTypes.bool,
        isLast: PropTypes.bool,
        onSelect: PropTypes.func
    };

    static defaultProps = {
        isFirst: false,
        isLast: false,
        onSelect: null
    };

    handleSelect = () => {
        const {id, onSelect} = this.props;

        onSelect(id);
    };

    handleKeyDown = filterKeyCodes(this.handleSelect);

    render() {
        const {name, isFirst, isLast, onSelect, index} = this.props;
        let arrowIcon = null;
        let text = null;

        if (!isFirst) {
            arrowIcon = <Icon className="rc-breadcrumbs-item-icon" name="chevron-right-small" />;
        }

        if (isLast || !isFunction(onSelect)) {
            text = (
                <span
                    className="rc-breadcrumbs-item-name"
                    data-test-automation-id="breadcrumbLink"
                    title={name}>
                    {name}
                </span>
            );
        } else {
            text = (
                <a
                    className="rc-breadcrumbs-item-name rc-breadcrumbs-item-link"
                    tabIndex={0}
                    onClick={this.handleSelect}
                    onKeyDown={this.handleKeyDown}
                    data-test-automation-id="breadcrumbLink"
                    title={name}>
                    {name}
                </a>
            );
        }

        return (
            <div className="rc-breadcrumbs-item" data-test-automation-id={`breadcrumb${index}`}>
                {arrowIcon}
                {text}
            </div>
        );
    }
}
