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

import {Icon} from '../Icon';

import {BreadCrumb} from './BreadCrumb';

export class BreadCrumbs extends Component {
    static propTypes = {
        iconName: PropTypes.string,
        items: PropTypes.arrayOf(
            PropTypes.shape({
                id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
                name: PropTypes.string
            })
        ),
        onSelect: PropTypes.func,
        testAutomationId: PropTypes.string,
        style: PropTypes.object
    };

    static defaultProps = {
        iconName: null,
        items: [],
        onSelect: null,
        testAutomationId: 'breadcrumbs',
        style: null,
        breadcrumbMaxWidth: 240
    };

    renderCrumb = (item, index = 0) => {
        const {items, onSelect} = this.props;
        const {id, name} = item;

        const isFirst = index <= 0;
        const isLast = index >= items.length - 1;

        return (
            <BreadCrumb
                key={id}
                id={id}
                name={name}
                isFirst={isFirst}
                isLast={isLast}
                onSelect={onSelect}
                index={index}
            />
        );
    };

    render() {
        const {iconName, items, style, onSelect, testAutomationId} = this.props;
        const className = classnames('rc-breadcrumbs', {
            'rc-breadcrumbs-no-handler': !isFunction(onSelect)
        });

        let icon = null;

        if (iconName) {
            icon = <Icon name={iconName} className="rc-breadcrumbs-icon" />;
        }

        return (
            <div style={style} className={className} data-test-automation-id={testAutomationId}>
                {icon}
                {items.map(this.renderCrumb)}
            </div>
        );
    }
}
