import React from 'react';
import PropTypes from 'prop-types';
import BSFormControl from 'react-bootstrap/lib/FormControl';
import classnames from 'classnames';
import {Icon} from '../../Icon';
import _ from 'lodash';
import {isElementFocused} from './datePickerHelpers';
import {FormControl} from '../FormControl';
import OutsideClickHandler from 'react-outside-click-handler';
import {KeyNames} from '../../../../utils/constants';
import {translate} from '../../../../utils';
import {wait} from '../../../utils/functions';

const toFnWithDate = str => ({date}) => translate(str, {date});

let instanceCounter = 0;

const WAIT_TIME_OUT_WHEN_BLUR = 150;

export class DatePickerBase extends FormControl {
    static propTypes = {
        ...FormControl.propTypes,
        inputProps: PropTypes.object,
        ariaLabel: PropTypes.string,
        disabled: PropTypes.bool,
        testAutomationId: PropTypes.string.isRequired,
        dayPickerPhrase: PropTypes.object
    };

    static defaultProps = {
        ...FormControl.defaultProps,
        ariaLabel: null,
        dayPickerPhrase: {
            calendarLabel: 'TRANSLATE:DATEPICKER_PHRASE_CALENDAR_LABEL',
            closeDatePicker: 'TRANSLATE:DATEPICKER_PHRASE_CLOSE_DATE_PICKER',
            focusStartDate: 'TRANSLATE:DATEPICKER_PHRASE_FOCUS_START_DATE',
            clearDate: 'TRANSLATE:DATEPICKER_PHRASE_CLEAR_DATE',
            clearDates: 'TRANSLATE:DATEPICKER_PHRASE_CLEAR_DATES',
            jumpToPrevMonth: 'TRANSLATE:DATEPICKER_PHRASE_JUMP_TO_PREV_MONTH',
            jumpToNextMonth: 'TRANSLATE:DATEPICKER_PHRASE_JUMP_TO_NEXT_MONTH',
            keyboardShortcuts: 'TRANSLATE:DATEPICKER_PHRASE_KEYBOARD_SHORTCUTS',
            showKeyboardShortcutsPanel: 'TRANSLATE:DATEPICKER_PHRASE_SHOW_KEYBOARD_SHORTCUTS_PANEL',
            hideKeyboardShortcutsPanel: 'TRANSLATE:DATEPICKER_PHRASE_HIDE_KEYBOARD_SHORTCUTS_PANEL',
            openThisPanel: 'TRANSLATE:DATEPICKER_PHRASE_OPEN_THIS_PANEL',
            enterKey: 'TRANSLATE:DATEPICKER_PHRASE_ENTER_KEY',
            leftArrowRightArrow: 'TRANSLATE:DATEPICKER_PHRASE_LEFT_ARROW_RIGHT_ARROW',
            upArrowDownArrow: 'TRANSLATE:DATEPICKER_PHRASE_UP_ARROW_DOWN_ARROW',
            pageUpPageDown: 'TRANSLATE:DATEPICKER_PHRASE_PAGE_UP_PAGE_DOWN',
            homeEnd: 'TRANSLATE:DATEPICKER_PHRASE_HOME_END',
            escape: 'TRANSLATE:DATEPICKER_PHRASE_ESCAPE',
            questionMark: 'TRANSLATE:DATEPICKER_PHRASE_QUESTION_MARK',
            selectFocusedDate: 'TRANSLATE:DATEPICKER_PHRASE_SELECT_FOCUSED_DATE',
            moveFocusByOneDay: 'TRANSLATE:DATEPICKER_PHRASE_MOVE_FOCUS_BY_ONE_DAY',
            moveFocusByOneWeek: 'TRANSLATE:DATEPICKER_PHRASE_MOVE_FOCUS_BY_ONE_WEEK',
            moveFocusByOneMonth: 'TRANSLATE:DATEPICKER_PHRASE_MOVE_FOCUS_BY_ONE_MONTH',
            moveFocustoStartAndEndOfWeek:
                'TRANSLATE:DATEPICKER_PHRASE_MOVE_FOCUSTO_START_AND_END_OF_WEEK',
            returnFocusToInput: 'TRANSLATE:DATEPICKER_PHRASE_RETURN_FOCUS_TO_INPUT',
            keyboardNavigationInstructions:
                'TRANSLATE:DATEPICKER_PHRASE_KEYBOARD_NAVIGATION_INSTRUCTIONS',

            chooseAvailableDate: 'TRANSLATE:DATEPICKER_PHRASE_CHOOSE_AVAILABLE_DATE',
            chooseAvailableStartDate: 'TRANSLATE:DATEPICKER_PHRASE_CHOOSE_AVAILABLE_START_DATE',
            chooseAvailableEndDate: 'TRANSLATE:DATEPICKER_PHRASE_CHOOSE_AVAILABLE_ENDDATE',
            dateIsUnavailable: 'TRANSLATE:DATEPICKER_PHRASE_DATE_IS_UNAVAILABLE',
            dateIsSelected: 'TRANSLATE:DATEPICKER_PHRASE_DATE_IS_SELECTED'
        }
    };

    constructor(props, ctx) {
        super(props, ctx);
        this.state = {
            isDayPickerFocused: false,
            isDayPickerVisible: false,
            isPreventDayPickerClosed: false,
            isInputFocusedFromOutside: true
        };
        this.instanceId = instanceCounter++;
    }

    componentDidMount() {
        this.setState({isInputFocusedFromOutside: true});
        this.calendarContainer.addEventListener('keydown', event => {
            if (this.state.isDayPickerVisible && event.key === KeyNames.Escape) {
                event.stopPropagation();
            }
        });
    }

    calendarContainer = null;

    onKeyDown = _.throttle(event => {
        switch (event.key) {
            case KeyNames.ArrowDown:
                this.onInputKeyDownArrowDown();
                break;

            case KeyNames.Escape:
            case KeyNames.Tab:
                this.closeDayPicker();
                break;

            default:
                break;
        }
    });

    onCalendarKeyUp = _.throttle(event => {
        if (event.key === KeyNames.Escape) {
            this.closeDayPicker();
            this.focusToInput();
        }
    });

    /** prevent dayPicker being closed after react-dates trigger blur on monthChange, yearChange */
    isPreventCloseDayPickerOnBlur = false;

    onInputKeyDownArrowDown = () => {
        this.showDayPicker();
        this.focusOnDateCell();
    };

    focusOnDateCell = () => {
        return this.setStatePromise({isDayPickerFocused: false}).then(() =>
            this.setStatePromise({isDayPickerFocused: true})
        );
    };

    blurDateCell = () => {
        return this.setStatePromise({isDayPickerFocused: false});
    };

    setStatePromise = state => {
        return new Promise(resolve => {
            this.setState(state, resolve);
        });
    };

    closeDayPicker() {
        return this.setStatePromise({
            isDayPickerVisible: false,
            isDayPickerFocused: false
        });
    }

    showDayPicker = () => {
        if (!this.state.isDayPickerVisible) {
            this.setState({
                isDayPickerVisible: true,
                isDayPickerFocused: false
            });
        }
    };

    handleFocusInput = () => {
        const {isInputFocusedFromOutside} = this.state;

        if (isInputFocusedFromOutside) {
            this.showDayPicker();
        }
    };

    handleToggleDayPickerDisplay = e => {
        if (!_.isEmpty(e)) {
            e.stopPropagation();
        }

        const {isDayPickerVisible} = this.state;

        if (isDayPickerVisible) {
            this.closeDayPicker();
        } else {
            this.showDayPicker();
        }
    };

    isFocusedInsideDayPickerContainer = () => isElementFocused(this.calendarContainer);

    focusToInput = () => this.focus();

    handleBlurDatePickerControl = () => {
        wait(WAIT_TIME_OUT_WHEN_BLUR).then(() => {
            if (!this.isPreventCloseDayPickerOnBlur && !this.isFocusedInsideDayPickerContainer()) {
                this.toggleIsInputFocusedFromOutside(true);
                this.closeDayPicker();
            }
        });
    };

    toggleIsInputFocusedFromOutside = isInputFocusedFromOutside => {
        return this.setStatePromise({isInputFocusedFromOutside});
    };

    handleMouseDownPreventCloseDayPicker = () => {
        this.isPreventCloseDayPickerOnBlur = true;
    };

    handleCloseDayPickerOnBlur = () => {
        this.isPreventCloseDayPickerOnBlur = false;
    };

    setContainerRef = el => (this.calendarContainer = el);

    handleOutsideClick = () => {
        this.toggleIsInputFocusedFromOutside(true);
        this.closeDayPicker();
    };

    /** @abstract */
    getDatePickerContainerClassName() {
        return '';
    }

    /** @abstract */
    renderDatePicker() {
        return null;
    }

    /** @abstract */
    getDisplayValue = () => null;

    /** @abstract */
    getPhrases() {
        const {
            calendarLabel,
            closeDatePicker,
            focusStartDate,
            clearDate,
            clearDates,
            jumpToPrevMonth,
            jumpToNextMonth,
            keyboardShortcuts,
            showKeyboardShortcutsPanel,
            hideKeyboardShortcutsPanel,
            openThisPanel,
            enterKey,
            leftArrowRightArrow,
            upArrowDownArrow,
            pageUpPageDown,
            homeEnd,
            escape,
            questionMark,
            selectFocusedDate,
            moveFocusByOneDay,
            moveFocusByOneWeek,
            moveFocusByOneMonth,
            moveFocustoStartAndEndOfWeek,
            returnFocusToInput,
            keyboardNavigationInstructions,

            chooseAvailableDate,
            chooseAvailableStartDate,
            chooseAvailableEndDate,
            dateIsUnavailable,
            dateIsSelected
        } = this.props.dayPickerPhrase;

        const phrases = {
            calendarLabel,
            closeDatePicker,
            focusStartDate,
            clearDate,
            clearDates,
            jumpToPrevMonth,
            jumpToNextMonth,
            keyboardShortcuts,
            showKeyboardShortcutsPanel,
            hideKeyboardShortcutsPanel,
            openThisPanel,
            enterKey,
            leftArrowRightArrow,
            upArrowDownArrow,
            pageUpPageDown,
            homeEnd,
            escape,
            questionMark,
            selectFocusedDate,
            moveFocusByOneDay,
            moveFocusByOneWeek,
            moveFocusByOneMonth,
            moveFocustoStartAndEndOfWeek,
            returnFocusToInput,
            keyboardNavigationInstructions,

            chooseAvailableDate: toFnWithDate(chooseAvailableDate),
            chooseAvailableStartDate: toFnWithDate(chooseAvailableStartDate),
            chooseAvailableEndDate: toFnWithDate(chooseAvailableEndDate),
            dateIsUnavailable: toFnWithDate(dateIsUnavailable),
            dateIsSelected: toFnWithDate(dateIsSelected)
        };

        _.forEach(phrases, (value, key) => {
            if (value === undefined) {
                phrases[key] = DatePickerBase.defaultProps[key];
            }
        });

        return phrases;
    }

    /** @abstract */
    handleMouseUpDayPickerContainer = () => {};

    handlePreventDefault = e => e.preventDefault();

    render() {
        const {testAutomationId, disabled, inputProps, dayPickerPhrase, ariaLabel} = this.props;
        const {keyboardNavigationInstructions} = dayPickerPhrase;
        const ariaDescribeId = `date-picker-input-describe-message-${this.instanceId}`;

        return (
            <OutsideClickHandler onOutsideClick={this.handleOutsideClick}>
                <div
                    ref={this.setContainerRef}
                    data-test-automation-id={testAutomationId}
                    className={classnames('rc-datepicker', {'rc-datepicker-disabled': disabled})}
                    onMouseDown={this.handleMouseDownPreventCloseDayPicker}
                    onKeyDown={this.handleCloseDayPickerOnBlur}
                    onKeyUp={this.handleCloseDayPickerOnBlur}
                    onBlur={this.handleBlurDatePickerControl}>
                    <Icon name="calendar" onClick={this.handleToggleDayPickerDisplay} />
                    <BSFormControl
                        onKeyDown={this.onKeyDown}
                        onFocus={this.handleFocusInput}
                        type="text"
                        ref="input"
                        value={this.getDisplayValue()}
                        onChange={this.handlePreventDefault}
                        aria-describedby={ariaDescribeId}
                        aria-label={ariaLabel}
                        {...inputProps}
                    />
                    <p className="sr-only" id={ariaDescribeId}>
                        {keyboardNavigationInstructions}
                    </p>
                    <div
                        data-test-automation-id="datePickerContainer"
                        className={`rc-datepicker-container ${this.getDatePickerContainerClassName()}`}
                        onKeyUp={this.onCalendarKeyUp}
                        onMouseUp={this.handleMouseUpDayPickerContainer}>
                        {this.renderDatePicker()}
                    </div>
                </div>
            </OutsideClickHandler>
        );
    }
}
