'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import {LinkContainer} from 'react-router-bootstrap';
import {NavItem} from 'react-bootstrap';
import {LinkProps} from 'react-router';

type TabItemProps = {
    children: React.ReactNode;
    to?: string;
    testAutomationId?: string;
    active?: boolean;
    onClick?: Function;
    eventKey?: any;
    activeKey?: any;
    tabIndex?: number;
} & Partial<LinkProps>;

export class TabItem extends React.Component<TabItemProps> {
    static get contextTypes() {
        return {
            router: PropTypes.object,
            isStyledAsTab: PropTypes.func
        };
    }

    static propTypes = {
        children: PropTypes.node.isRequired,
        to: PropTypes.string,
        testAutomationId: PropTypes.string,
        active: PropTypes.bool,
        onClick: PropTypes.func,
        eventKey: PropTypes.any,
        activeKey: PropTypes.any
    };

    static defaultProps = {
        testAutomationId: null,
        to: null,
        active: null,
        onClick: null,
        eventKey: null,
        activeKey: null
    };

    componentDidMount() {
        const {testAutomationId} = this.props;
        const node = ReactDOM.findDOMNode(this) as any;
        if (node) {
            node.setAttribute('data-test-automation-id', testAutomationId);
        }
    }

    handleClick = event => {
        if (this.props.onClick) {
            this.props.onClick(event);
        }
    };

    getTabProps(): any {
        let {testAutomationId, ...props} = this.props;

        props = {
            role: 'tab',
            ...props,
            onClick: this.handleClick,
            tabIndex: -1
        };

        return props;
    }

    render() {
        const {to, children} = this.props;

        const props = this.getTabProps();

        if (to) {
            return (
                <LinkContainer {...props}>
                    <NavItem>{children}</NavItem>
                </LinkContainer>
            );
        }

        return <NavItem {...props}>{children}</NavItem>;
    }
}
