import PropTypes from 'prop-types';
import React from 'react';
import isEmpty from 'lodash/isEmpty';
import get from 'lodash/get';
import moment from 'moment';
import { isRequired, isRequiredIf, composeValidators, combineValidators } from 'revalidate';
import ReactTooltip from 'react-tooltip';

import { requestAppointmentAvailability } from '../../utils/api';
import { isValidDate, isFutureDate, isNotTooFarInFuture } from '../../utils/validators';
import { jss } from '../../utils/styles';
import styles from './styles/FindAppointment';
import {
    DATE_FORMAT_DISPLAY as DEFAULT_DATE_FORMAT_DISPLAY,
    DATE_FORMAT_INPUT_DISPLAY,
    TIME_FORMAT,
    ISO_FORMAT,
} from '../../constants/dateTimeFormats';
import { CLIENT_INFORMATION, SELECT_APPOINTMENT } from '../../constants/formSections';
import {
    WIDGET_TYPES,
    APPOINTMENT_TOUR_TYPE_SELF_GUIDED_TEXT_VALUE,
    SELF_GUIDED_TOUR_PROVIDER_GENERIC
} from '../../constants/config';

import CalendarInput from '@nestio/pam/lib/components/CalendarInput';
import Input from './Input';
import FieldGroup from './FieldGroup';
import FormHeader from './FormHeader';
import { InputSingleSelect } from './InputSelect';
import FormErrorsAriaNotification from './FormErrorsAriaNotification';
import isEqual from 'lodash/isEqual';

jss.createStyleSheet(styles, { named: false }).attach();

const createValidator = props => combineValidators({
    date: composeValidators(
        isRequired,
        isValidDate,
        isFutureDate,
        isNotTooFarInFuture(props.employeeGroup.max_days_in_advance_to_book_tours),
    )('Viewing date'),
    time: isRequired('Viewing time'),
    tour_type: isRequired('Tour type'),
    platform_of_choice: isRequiredIf(values => values.tour_type === 'video')('Platform of choice'),
    platform_of_choice_details: isRequiredIf(values => values.tour_type === 'video')('Number, Email, or ID for video call')
});

export const renderPreferredTourTypeSelectLabel = (option) => {
    return (
        <div className="preferred-tour-type-select-option">
            <div className="preferred-tour-type-select-option-label">{option.label}</div>
            <div className="preferred-tour-type-select-option-helper-text">{option.helperText}</div>
        </div>
    );
};

export default class FindAppointment extends React.Component {
    constructor (props) {
        super(props);

        this.state = {
            submitting: false,
            data: {
                date: '',
                time: null,
                ...props.appointment
            },
            errors: {},
            responseErrors: null,
        };

        this.handleSubmit = this.handleSubmit.bind(this);
        this.bindChangeHandler = this.bindChangeHandler.bind(this);
        this.getTourTypeHelperText = this.getTourTypeHelperText.bind(this);
    }

    componentDidUpdate(prevProps, prevState) {
        const { data } = this.state;
        const selfGuidedTourProvider = this.props.employeeGroup?.self_guided_tour_provider;
        const selfGuidedTourUrl = this.props.employeeGroup?.self_guided_tour_url;
        if (
            prevState.data.tour_type !== this.state.data.tour_type &&
            this.state.data.tour_type === APPOINTMENT_TOUR_TYPE_SELF_GUIDED_TEXT_VALUE &&
            selfGuidedTourProvider !== SELF_GUIDED_TOUR_PROVIDER_GENERIC && !!selfGuidedTourUrl
        ) {
            this.props.setFormData({
                appointment: {
                    ...this.state.data,
                }
            });
            this.props.setFormSection(CLIENT_INFORMATION);
        }

        const tourTypeChanged = prevState.data.tour_type !== data.tour_type;
        const dateChanged = prevState.data.date !== data.date ;
        if ((tourTypeChanged || dateChanged) && !!data.tour_type && !!data.date) {
            // fetch available times when tour type and date both have been selected
            requestAppointmentAvailability(data.date, data.tour_type).then(response => {
                const { available_times: availableTimes } = response.body;
                this.props.setTimeChoices(availableTimes);
            }).catch(() => {
                this.setState({
                    responseErrors: 'There was an error fetching availabilities. Please try again later.',
                });
            });
        }

        const timeChoicesChanged = !isEqual(prevProps.timeChoices, this.props.timeChoices);
        // Clear time if the selected choice is no longer available
        if (timeChoicesChanged && data.time && !this.props.timeChoices.some(choice => choice.value === data.time)) {
            this.bindChangeHandler('time')(null);
        }
    }

    validate () {
        const validator = createValidator(this.props);
        const errors = validator(this.state.data);
        const isValid = isEmpty(errors);

        this.setState({ errors });

        return isValid;
    }

    handleSubmit (e) {
        e.preventDefault();
        const { data } = this.state;

        const isValid = this.validate();

        if (!isValid) {
            return;
        }

        const appointmentTime = moment(`${data.date}:${data.time}`, `${DEFAULT_DATE_FORMAT_DISPLAY}:${TIME_FORMAT}`).format(ISO_FORMAT);
        const appointment = {
            ...data,
            start: appointmentTime
        };

        this.props.setFormData({ appointment });

        this.setState({ submitting: true });

        return requestAppointmentAvailability(data.date, appointment.tour_type)
            .then(response => {
                const { available_times: availableTimes, next_available_date: nextAvailableDate } = response.body;

                this.props.setAvailableTimes(availableTimes);
                this.props.setNextAvailableDate(nextAvailableDate);
                this.props.setFormSection(SELECT_APPOINTMENT);
            })
            .catch(errorResponse => {
                const { errors, available_times: availableTimes } = errorResponse.response.body;

                this.setState({ submitting: false });

                if (!availableTimes && errors) {
                    const error = get(errors, 'from_date[0]') || get(errors, 'tour_type[0]') || 'Cannot select requested time';
                    this.setState({
                        responseErrors: error,
                        errors: {},
                    });
                }
            });
    }

    bindChangeHandler (field) {
        return (value) => {
            this.setState({
                data: {
                    ...this.state.data,
                    [field]: value
                }
            });
        };
    };

    getTourTypeHelperText () {
        if (!this.props.tourTypeOptions || !this.state.data.tour_type) {
            return null;
        }

        const selectedOption = this.props.tourTypeOptions.find(o => o.value === this.state.data.tour_type);
        if (!selectedOption) {
            return null;
        }

        return selectedOption.helperText;
    }

    render () {
        const {
            tourTypeOptions,
            platformOfChoiceOptions,
            employeeGroup: { max_days_in_advance_to_book_tours: maxDaysAhead },
        } = this.props;
        const { errors, responseErrors, data, submitting } = this.state;

        return (
            <form onSubmit={this.handleSubmit}>
                <FormHeader />
                <FormErrorsAriaNotification errors={errors}/>

                <div className="cheryl__row">
                    <FieldGroup
                        labelText="Preferred Tour Type"
                        containerClassName="cheryl__select-tour-type"
                        helpText={this.getTourTypeHelperText()}
                        error={errors.tour_type}
                    >
                        <InputSingleSelect
                            ariaLabel="Tour Type"
                            placeholder="Select tour type"
                            value={data.tour_type}
                            options={tourTypeOptions}
                            onChange={this.bindChangeHandler('tour_type')}
                            renderOptionLabel={renderPreferredTourTypeSelectLabel}
                        />
                    </FieldGroup>
                </div>

                {data.tour_type === 'video' && (
                    <div className="cheryl__row">
                        <FieldGroup
                            labelText="Platform of Choice"
                            containerClassName="cheryl__col-1-2 cheryl__select-platform-choice-options"
                            error={errors.platform_of_choice}
                        >
                            <InputSingleSelect
                                ariaLabel="Platform of Choice"
                                placeholder="Select platform"
                                value={data.platform_of_choice}
                                name="platform_of_choice"
                                options={platformOfChoiceOptions}
                                onChange={this.bindChangeHandler('platform_of_choice')}
                            />
                        </FieldGroup>

                        <FieldGroup
                            labelText="Number, Email, or ID for video call"
                            containerClassName="cheryl__col-1-2 cheryl__select-platform-choice-details"
                            error={errors.platform_of_choice_details}
                        >
                            <Input
                                aria-label="Number, Email, or ID for video call"
                                placeholder="Enter here"
                                onChange={(event) => this.bindChangeHandler('platform_of_choice_details')(event.target.value)}
                                defaultValue={data.platform_of_choice_details}
                            />
                        </FieldGroup>
                    </div>
                )}

                <div className="cheryl__row">
                    <FieldGroup
                        labelText="Date"
                        containerClassName="cheryl__col-1-2 cheryl__select-date"
                        error={errors.date}
                    >
                        <div data-tip={!data.tour_type ? 'Please select a tour type' : null}>
                            <CalendarInput
                                value={data.date}
                                format={DATE_FORMAT_INPUT_DISPLAY}
                                placeholder="Select date"
                                mask="99/99/9999"
                                maskChar=" "
                                minDate={moment()}
                                maxDate={maxDaysAhead ? moment().add(maxDaysAhead, 'days') : undefined}
                                ariaHidden={true}
                                onChange={this.bindChangeHandler('date')}
                                defaultValue=""
                                disabled={!data.tour_type}
                            />
                        </div>
                        <ReactTooltip place="top" effect="solid" />
                    </FieldGroup>
                    <FieldGroup
                        labelText="Time"
                        containerClassName="cheryl__col-1-2 cheryl__select-time"
                        error={errors.time}
                    >
                        <div data-tip={!data.tour_type || !data.date ? 'Please select a tour date' : null}>
                            <InputSingleSelect
                                ariaLabel="Time"
                                inputName="time"
                                placeholder="Select time"
                                value={data.time}
                                options={this.props.timeChoices}
                                onChange={this.bindChangeHandler('time')}
                                disabled={!data.date || !data.tour_type}
                                key={data.time} // force re-render when unsetting time
                            />
                        </div>
                        <ReactTooltip place="top" effect="solid" />
                    </FieldGroup>
                </div>

                <div>{responseErrors}</div>

                <div className="cheryl__row">
                    <button className="cheryl__button-primary" disabled={submitting}>
                        Continue
                    </button>
                </div>
            </form>
        );
    }
}

FindAppointment.propTypes = {
    setFormSection: PropTypes.func.isRequired,
    setFormData: PropTypes.func.isRequired,
    timeChoices: PropTypes.array.isRequired,
    setAvailableTimes: PropTypes.func.isRequired,
    setNextAvailableDate: PropTypes.func.isRequired,
    appointment: PropTypes.shape({
        start: PropTypes.string,
        expiration_date: PropTypes.string,
        location: PropTypes.string,
        tour_type: PropTypes.string,
        platform_of_choice: PropTypes.string,
        platform_of_choice_details: PropTypes.string
    }),
    tourTypeOptions: PropTypes.array,
    platformOfChoiceOptions: PropTypes.array,
    employeeGroup: PropTypes.object,
    setTimeChoices: PropTypes.func,
};

FindAppointment.contextTypes = {
    widgetType: PropTypes.oneOf(WIDGET_TYPES).isRequired,
};
