import React, { Component } from 'react';
import DayPicker from 'react-day-picker';
import 'react-day-picker/lib/style.css';
import PropTypes from 'prop-types';
import { InputText } from '../../atom/InputText/InputText';


/**
 * A stateful Common Component for Desktop Date Range Calendar. It uses react-day-picker.
 */

class DesktopDateRangeCalendar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            popVisible: false,
            count: 0
        };

        this.handleClickoutside = this.handleClickoutside.bind(this);
        this.handleOutsideClickCalendar = this.handleOutsideClickCalendar.bind(this);
        this.dayPicker = React.createRef();
    }

    handleClickoutside() {
        if (!this.state.popVisible) {
            document.addEventListener('click', this.handleOutsideClickCalendar, false);
        } else {
            document.removeEventListener('click', this.handleOutsideClickCalendar, false);
        }

        this.setState(prevState => ({
            popVisible: !prevState.popVisible,
        }));

    }
    handleOutsideClickCalendar(e) {
        if (this.node.contains(e.target)) {
            return;
        }
        this.handleClickoutside();
    }

    toStayOn = () => {
        this.setState(prevState => ({
            popVisible: !prevState.popVisible,
        }));
        document.onkeyup = (event) => {
            if (event.key === 'Enter') {
                this.setState({ popVisible: true });
            }
        };
    }

    onKeypress = (event) => {
        if (event.keyCode === 13) {
            setTimeout(() => {
                var pre = document.getElementsByClassName('DayPicker-NavButton DayPicker-NavButton--prev DayPicker-NavButton--interactionDisabled');
                pre[0].setAttribute('tabindex', '-1');
                var next = document.getElementsByClassName('DayPicker-NavButton DayPicker-NavButton--next');
                next[0].setAttribute('tabindex', '-1');
                var divs = document.getElementsByClassName('DayPicker-wrapper');
                divs[0].setAttribute('tabindex', '-1');

            }, 500);
            this.setState({popVisible : !this.state.popVisible});
        }
        if (event.keyCode === 27) {
            this.setState({ popVisible: false });
        }
    }

    handleFocus = (event) => {
        if (this.state.count === 0) {
            var pre = document.getElementsByClassName('DayPicker-NavButton DayPicker-NavButton--prev');
            pre[0].setAttribute('tabindex', '0');
            var next = document.getElementsByClassName('DayPicker-NavButton DayPicker-NavButton--next');
            next[0].setAttribute('tabindex', '0');
            var divs = document.getElementsByClassName('DayPicker-wrapper');
            divs[0].setAttribute('tabindex', '0');
            this.setState({ count: 1 });
        }
        if (event.shiftKey && event.key === 'ArrowUp') {
            this.dayPicker.current.showNextMonth();
        }
        else {
            if (event.shiftKey && event.key === 'ArrowDown') {
                this.dayPicker.current.showPreviousMonth();
            }
        }   
        if (event.keyCode === 27) {
            this.setState({ popVisible: false });
        }
    }

    render() {
        const { from, to } = this.props;
        const modifiers = { start: from, end: to };

        return (
            <div className={'jp-daterange-container ' + this.props.parentClassName} ref={node => { this.node = node; }}>
                <div role='presentation' aria-live='assertive' onClick={this.handleClickoutside} className={this.state.popVisible ? 'input-dropduparrow' : 'input-dropdownarrow'}>
                    <InputText
                        onClick={this.props.onToggleDateRangeCalendarInput}
                        value={((from && !to && `${from.toUTCString().slice(5, 16)} - ${from.toUTCString().slice(5, 16)}`) ||
                            (from && to && `${from.toUTCString().slice(5, 16)} - ${to.toUTCString().slice(5, 16)}`))}
                        type='text'
                        id='txtDateRange'
                        readOnly
                        aria-label={this.state.popVisible ? 'calendar expanded' : 'calendar collapsed'}
                        aria-autocomplete='list'
                        onKeyDown={this.onKeypress}
                    />
                </div>
                {this.state.popVisible && (
                    <DayPicker
                        {...this.props}
                        className='Selectable'
                        month={from}
                        months={this.props.months}
                        numberOfMonths={this.props.numberOfMonths}
                        selectedDays={this.props.selectedDays}
                        modifiers={modifiers}
                        showOutsideDays
                        onDayClick={this.props.handleDayClick}
                        disabledDays={
                            {
                                before: this.props.before,
                                after: this.props.after
                            }}
                        fromMonth={this.props.fromMonth}
                        toMonth={this.props.toMonth}
                        onKeyDown={this.handleFocus}
                        ref={this.dayPicker}
                    />
                )}
            </div>
        );
    }
}
export default DesktopDateRangeCalendar;

DesktopDateRangeCalendar.defaultProps = {
    numberOfMonths: 2,
    isOpen: false,
    from: new Date(),
    to: new Date(),
    parentClassName: ''
};

DesktopDateRangeCalendar.propTypes = {
    /** onClick Input text */
    onClick: PropTypes.func,
    /** flag to open calendar */
    isOpen: PropTypes.oneOfType([
        PropTypes.bool,
        PropTypes.number
    ]),
    /** number of months to shown */
    numberOfMonths: PropTypes.number,
    /** selected days to shown */
    selectedDays: PropTypes.array,
    /** handleDayClick to select day rang  */
    handleDayClick: PropTypes.func,
    /** disabled days before current days */
    before: PropTypes.instanceOf(Date),
    /** disabled days after current days */
    after: PropTypes.instanceOf(Date),
    /** initial month to show */
    fromMonth: PropTypes.instanceOf(Date),
    /** Current Date  */
    from: PropTypes.instanceOf(Date).isRequired,
    /** Current Date +2Days */
    to: PropTypes.instanceOf(Date).isRequired,
    /** to month   */
    toMonth: PropTypes.instanceOf(Date),
    /** To open and close calendar on click of input */
    onToggleDateRangeCalendarInput: PropTypes.func,
    /** Months options array */
    months: PropTypes.array,
    /** Class applied to parent container for additional styling */
    parentClassName: PropTypes.string
};