import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Draggable from 'react-draggable';
import moment from 'moment';
import classnames from 'classnames';

export const TIMEOUT = 100;
export const MAX_DRAG = 3;

export default class DraggableTimeSelector extends Component {
    constructor(){
        super();
        this.state = {
            leftBound: 0,
            currentDrag: null
        };


        this.calculateLeftBound = this.calculateLeftBound.bind(this);
        this.onDragStop = this.onDragStop.bind(this);
        this.onDragStart = this.onDragStart.bind(this);
        this.onDrag = this.onDrag.bind(this);
    }

    componentWillUnmount(){
        if (this._timeout){
            clearTimeout(this._timeout);
        }
    }

    calculateLeftBound(el){
        if (el){
             const containerWidth = el.offsetWidth;
             const childWidth = el.scrollWidth;

             const leftBound = Math.max(0, childWidth - containerWidth);

             this.setState({
                 leftBound: -(leftBound)
             });

        }
    }

    selectTime(option){
        if (this.state.currentDrag && Math.abs(this.state.currentDrag) > MAX_DRAG) {
            return;
        }

        this.props.selectTime(option);
    }

    onDragStart(){
        this.setState({ currentDrag: 0 });
        if (this._timeout) {
            clearTimeout(this._timeout);
        }
    }

    onDragStop(){
        this._timeout = setTimeout(() => {
            this.setState({ currentDrag: null });
            delete this._timeout;
        }, TIMEOUT);
    }

    onDrag(e, ui){
        const delta = ui.deltaX;
        this.setState((prevState) => {
            return { currentDrag: prevState.currentDrag + delta };
        });
    }

    render(){
        const { classes, times } = this.props;
        const timeElements = times.map(option => {
            const label = moment(option, 'HH:mm').format('h:mma');

            return (
                <button
                    className={classnames(classes.button, classes.timeItem)}
                    key={option}
                    onClick={() => this.selectTime(option)}
                >
                    {label}
                </button>
            );
        });

        return (
            <Draggable
                axis="x"
                bounds={{
                    right: 0,
                    left: this.state.leftBound
                }}
                onStart={this.onDragStart}
                onStop={this.onDragStop}
                onDrag={this.onDrag}
            >
                <div ref={this.calculateLeftBound} className={classes.timeContainer}>{ timeElements }</div>
            </Draggable>
        );
    }
}

DraggableTimeSelector.propTypes = {
    classes: PropTypes.object.isRequired,
    times: PropTypes.array.isRequired,
    selectTime: PropTypes.func.isRequired
};
