import * as React from 'react'
import { connect} from 'react-redux'
import * as cx from 'classnames'
import { Tray } from './tray'
import { TrayItem } from './tray-item'
import { Row } from './row'
import { OpenableComponent } from './openable-component'
import { TrayOverflowProps, TrayOverflowComponentProps } from '../interfaces'
import { getTrayItem } from '../selectors'
import { openTrayItem, closeTrayItem, toggleTrayItem } from '../actions'

const styles = require('../../src/styles/components/tray-item.scss')

const TRAY_OVERFLOW_BUTTON_KEY = 'trayOverflowButton'

class TrayOverflowComponent extends OpenableComponent<TrayOverflowComponentProps> {

    public static defaultProps = {
        align: 'center',
        width: 500,
    }
    public button: TrayItem

    public setButtonRef = (e: TrayItem) => this.button = e

    public componentDidMount() {
        super.componentDidMount()
        this.setContainerRef(this.button.container)
    }

    public renderOverflow() {
        const {trayItem, children, width} = this.props
        if (!trayItem || !trayItem.open) return null

        return (
            <div
                className={this.classNames()}
                style={{minWidth: `${width}px`}}>
                {children}
            </div>
        )
    }

    public render() {
        return (
            <TrayItem
                ref={this.setButtonRef}
                name={TRAY_OVERFLOW_BUTTON_KEY}
                text="..."
                tooltip="See more"
                onClick={this.handleClick}
                active={this.isActive()}
                className={styles.overflowButton}>
                {this.renderOverflow()}
            </TrayItem>
        )
    }

    public isActive() {
        return this.props.trayItem.open
    }

    public handleClose() {
        this.props.closeTrayItem(this.props.trayName, TRAY_OVERFLOW_BUTTON_KEY)
    }

    protected handleClick = () => {
        this.props.toggleTrayItem(this.props.trayName, TRAY_OVERFLOW_BUTTON_KEY)
    }

    protected classNames = () => cx(
        styles.overflowContainer,
        {
            [styles.overflowRight]: this.props.align === 'right',
            [styles.overflowLeft]: this.props.align === 'left',
            [styles.overflowCenter]: this.props.align === 'center',
        },
    )
}

const mapStateToProps = (state: any, ownProps: TrayOverflowProps) => ({
    trayItem: getTrayItem(state, ownProps.trayName, TRAY_OVERFLOW_BUTTON_KEY),
})

const mapDispatchToProps = {
    openTrayItem,
    closeTrayItem,
    toggleTrayItem,
}

export const TrayOverflow = connect(mapStateToProps, mapDispatchToProps)(TrayOverflowComponent)
