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

import { DATE_FORMAT, DATE_FORMAT_DISPLAY_SELECTOR } from '../../constants/dateTimeFormats';
import styles from './styles/DateSelector';
import DraggableTimeSelector from './DraggableTimeSelector';
import NextAvailableSelector from './NextAvailableSelector';
import DesktopDayChoices from './DesktopDayChoices';
import DesktopTimeSelector from './DesktopTimeSelector';
import Loading from './Loading';

export function NoAvailability({ classes }) {
    return (
        <div className={classes.nextAvailableContainer}>
            <div className={classes.noAvailability}>No Availability</div>
        </div>
    );
}

NoAvailability.propTypes = {
    classes: PropTypes.object.isRequired
};

export class DateSelector extends Component {
    constructor() {
        super();
        this.state = {
            times: null,
            nextAvailableDate: null,
            noAvailableTimes: false
        };

        this.incrementDate = this.incrementDate.bind(this);
        this.decrementDate = this.decrementDate.bind(this);
    }

    componentDidUpdate(prevProps) {
        if (prevProps.date !== this.props.date || prevProps.tour_type !== this.props.tour_type) {
            this.setState({ times: null, nextAvailableDate: null, noAvailableTimes: false });
            this.fetchAvailableTimes();
        }
    }

    componentDidMount() {
        this.fetchAvailableTimes(true);
    }

    decrementDate() {
        const decrement = this.props.isMobile ? 1 : 7;
        const newDate = moment(this.props.date, DATE_FORMAT).subtract(decrement, 'd');

        if (newDate.isBefore(moment(), 'd')) {
            return this.props.updateFormData('date', moment().format(DATE_FORMAT));
        }

        this.props.updateFormData('date', newDate.format(DATE_FORMAT));
    }

    fetchAvailableTimes(refetchWithNextDateAvailable) {
        this.props.date && this.props.API.fetchAvailableTimes(this.props.date, this.props.tour_type).then((data) => {
            const { available_times: availableTimes, next_available_date: nextAvailableDate } = data;

            if (availableTimes.length) {
                this.setState({ times: availableTimes });
            } else if (nextAvailableDate) {
                if (refetchWithNextDateAvailable) {
                    this.props.updateFormData('date', nextAvailableDate);
                } else {
                    this.setState({ nextAvailableDate });
                }
            } else {
                this.setState({ noAvailableTimes: true });
            }

            if (this.props.time) {
                const hasCurrentTime = availableTimes.indexOf(this.props.time) > -1;
                if (!hasCurrentTime) {
                    this.props.updateFormData('time', null);
                }
            }
        });
    }

    incrementDate() {
        const increment = this.props.isMobile ? 1 : 7;
        const newDate = moment(this.props.date, DATE_FORMAT).add(increment, 'd');

        if (this.props.maxDaysAhead) {
            const maxDate = moment().add(this.props.maxDaysAhead, 'd');
            if (newDate.isAfter(maxDate, 'd')) {
                return this.props.updateFormData('date', maxDate.format(DATE_FORMAT));
            }
        }

        this.props.updateFormData('date', newDate.format(DATE_FORMAT));
    }

    renderDate() {
        const { isMobile, classes, updateFormData, date, maxDaysAhead } = this.props;
        if (isMobile) {
            const dateLabel = moment(date, DATE_FORMAT).format(DATE_FORMAT_DISPLAY_SELECTOR);
            return <span className={classes.dayLabel}>{dateLabel}</span>;
        } else {
            return <DesktopDayChoices classes={classes} date={date} updateFormData={updateFormData} maxDaysAhead={maxDaysAhead} />;
        }
    }

    render() {
        const {
            classes,
            formErrors,
            updateFormData,
            selectTime,
            isMobile,
            showValidationErrors,
            date,
            time,
            disabled,
            maxDaysAhead,
        } = this.props;
        const { nextAvailableDate, times, noAvailableTimes } = this.state;
        const TimeSelector = isMobile ? DraggableTimeSelector : DesktopTimeSelector;

        const canGoBack = isMobile ?
            moment(date, DATE_FORMAT).isAfter(moment(), 'd') :
            moment(date, DATE_FORMAT).startOf('isoWeek').subtract(1, 'd').isAfter(moment(), 'd');
        const canGoForward = !maxDaysAhead ||
            (isMobile ?
                moment(date, DATE_FORMAT).isBefore(moment().add(maxDaysAhead, 'd'), 'd') :
                moment(date, DATE_FORMAT).endOf('isoWeek').add(1, 'd').isSameOrBefore(moment().add(maxDaysAhead, 'd'), 'd'));

        const errorText = (formErrors && showValidationErrors) ? formErrors.time : '';

        return (
            <div className={classnames(classes.dateSelector, {
                ['disabled']: disabled
            })}>
                <div className={classes.dateSelectorContent}>
                    <div className={classes.header}>Choose a Time</div>
                    <div className={classes.daySelector}>
                        <button
                            className={classnames(classes.changeDay, !canGoBack && classes.changeDayDisabled)}
                            onClick={canGoBack ? this.decrementDate : null}
                            disabled={!canGoBack}
                        >
                            <i className="ni ni-angle-left" />
                        </button>
                        {' '}
                        {this.renderDate()}
                        {' '}
                        <button
                            className={classnames(classes.changeDay, !canGoForward && classes.changeDayDisabled)}
                            onClick={canGoForward ? this.incrementDate : null}
                            disabled={!canGoForward}
                        >
                            <i className="ni ni-angle-right" />
                        </button>
                    </div>
                    <div className={isMobile ? classes.timeSelector : null}>
                        {times && <TimeSelector time={time} classes={classes} times={times} selectTime={selectTime} errorText={errorText} />}
                        {nextAvailableDate && <NextAvailableSelector classes={classes} nextAvailableDate={nextAvailableDate} updateFormData={updateFormData} />}
                        {noAvailableTimes && <NoAvailability classes={classes} />}
                        {!times && !nextAvailableDate && !noAvailableTimes && <Loading />}
                    </div>
                </div>
            </div >
        );
    }
}

DateSelector.defaultProps = {
    isMobile: true
};

DateSelector.propTypes = {
    API: PropTypes.object.isRequired,
    classes: PropTypes.object.isRequired,
    date: PropTypes.string.isRequired,
    time: PropTypes.string,
    tour_type: PropTypes.any,
    disabled: PropTypes.bool,
    formErrors: PropTypes.object,
    updateFormData: PropTypes.func.isRequired,
    showValidationErrors: PropTypes.bool,
    selectTime: PropTypes.func.isRequired,
    isMobile: PropTypes.bool,
    maxDaysAhead: PropTypes.number,
};

export default injectSheet(styles)(DateSelector);
