import React, { Component } from 'react';

import './Tabs.scss';

export class Tabs extends Component {

    constructor(props) {
        super(props);
        
        this.initProps = this.initProps.bind(this);

        this.state = {
            activeTab: 0
        };
    }


    componentWillMount() {
        this.initProps(this.props.activeTab);
    }

    componentWillReceiveProps(props) {
        this.initProps(props.activeTab != this.props.activeTab ? props.activeTab : null);
    }


    initProps(activeTab) {
        let newState = {};
        if (activeTab || activeTab == 0) {
            this.setState({ activeTab });
        }
    }

    setActive(tab) {
        this.setState({ activeTab: tab });
    }


    render() {
        let 
            cn = "tabs",
            { 
                className,
                size,
                children

            } = this.props,
            { activeTab } = this.state;


        let ch = Array.isArray(this.props.children) ? this.props.children : [this.props.children];

        if (!ch) {
            throw new Error('Tabs must contain at least one Tab');
        }

        ch = ch.filter(t => t != null);

        let menuItems = ch
            .map($panel => typeof $panel === 'function' ? $panel() : $panel)
            .map(($panel, index) => {
                let title = $panel.props.title;
                let classes;
                if ($panel.props.disabled) {
                    classes = "tab disabled";
                } else {
                    classes = this.state.activeTab === index ? "tab active" : "tab";
                }

                return (
                    <button key={index} className={ classes } onClick={this.setActive.bind(this, index)} disabled={ $panel.props.disabled }>
                        {title} {$panel.props.titleDecorator} 
                    </button>
                );
            })

        let panel = activeTab > -1 && activeTab < ch.length ? ch[ activeTab ] : null;
        
        if (className) {
            cn += " " + className;
        }
        if (size) {
            cn += " " + size;
        }

        return (
            <div className={ cn }>
                <div className="tab-menu">
                    { menuItems }
                </div>
                <div>
                    { panel }
                </div>
            </div>
        );
    }

}


//<Tab label />
export const Tab = (props) => {
    let cn = props.className ? "tab " + props.className : "tab";
    return (
        <div className={ cn }>
            { props.children }
        </div>
    );
}

