import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import {isFunction} from 'lodash';
import {Collapse} from 'react-bootstrap';
import {filterKeyCodes} from '../../utils/functions';

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

export class AccordionItem extends PureComponent {
    static propTypes = {
        title: PropTypes.node.isRequired,
        name: PropTypes.string,
        isExpanded: PropTypes.bool,
        onToggle: PropTypes.func,
        children: PropTypes.node,
        lazy: PropTypes.bool,
        testAutomationId: PropTypes.string
    };

    static defaultProps = {
        name: null,
        onToggle: null,
        isExpanded: false,
        children: null,
        lazy: false,
        testAutomationId: 'accordionItem'
    };

    static getDerivedStateFromProps(props, state) {
        const {isExpanded} = props;
        const {isShown} = state;

        if (!isShown && isExpanded) {
            return {isShown: true};
        }

        return state;
    }

    state = {
        isShown: this.props.isExpanded
    };

    handleClick = () => {
        const {onToggle, name} = this.props;

        if (isFunction(onToggle)) {
            onToggle(name);
        }
    };

    handleKeyDown = filterKeyCodes(this.handleClick);

    renderChildren() {
        const {lazy, children} = this.props;
        const {isShown} = this.state;

        if (!isShown && lazy) {
            return null;
        }

        return children;
    }

    render() {
        const {title, isExpanded, testAutomationId} = this.props;
        const arrow = isExpanded ? 'chevron-up-big' : 'chevron-down-big';

        const className = classnames('rc-accordion-item', {
            'rc-accordion-item-expanded': isExpanded
        });

        return (
            <div className={className} data-test-automation-id={testAutomationId}>
                <div
                    className="rc-accordion-item-header"
                    onClick={this.handleClick}
                    onKeyDown={this.handleKeyDown}
                    tabIndex="0"
                    role="button"
                    aria-expanded={isExpanded}
                    aria-label={title}
                    data-test-automation-id="accordionItemHead">
                    <Block addHorizontalOffset cancelBottomOffset>
                        <Block inline className="pull-left">
                            <Icon name={arrow} />
                        </Block>
                        <h3 role="presentation" data-test-automation-id="assignToggleText">
                            {title}
                        </h3>
                    </Block>
                </div>
                <Collapse in={isExpanded} data-test-automation-id="accordionItemContent">
                    <div>{this.renderChildren()}</div>
                </Collapse>
            </div>
        );
    }
}
