import PropTypes from 'prop-types';
import React, { Component, Fragment, Suspense, lazy } from 'react';
import Media from 'react-media';
import moment from 'moment';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { ThemeProvider } from 'react-jss';
import castArray from 'lodash/castArray';
import each from 'lodash/each';
import get from 'lodash/get';
import omit from 'lodash/omit';
import set from 'lodash/set';
import isString from 'lodash/isString';
import isObject from 'lodash/isObject';
import isEmpty from 'lodash/isEmpty';
import reduce from 'lodash/reduce';
import cloneDeep from 'lodash/cloneDeep';
import isUndefined from 'lodash/isUndefined';
import pick from 'lodash/pick';

import {
    EMPLOYEEGROUP_FIELD_CONFIG_CHOICES,
    BUDGET_CHOICES,
    UPDATED_DEFAULT_ACCENT_COLOR,
    ERROR_RESPONSE_TYPE_START,
    ERROR_RESPONSE_TYPE_OTHER,
    NONE,
    APPOINTMENT_STATUS_CANCELLED,
    APPOINTMENT_STATUS_CONFIRMED,
    SMS_OPT_IN_MARKETING_ENABLED,
    APPOINTMENT_TOUR_TYPE_GUIDED,
    APPOINTMENT_TOUR_TYPE_SELF_GUIDED,
    APPOINTMENT_TOUR_TYPE_GUIDED_TEXT_VALUE,
    APPOINTMENT_TOUR_TYPE_SELF_GUIDED_TEXT_VALUE,
    NEARBY_COMMUNITY_SCHEDULING_TIME_DELTA_IN_MINUTES_FROM_PREVIOUS_APPOINTMENT,
    formatAmenityField,
    SELF_GUIDED_TOUR_OPTION_V3,
    SELF_GUIDED_TOUR_PROVIDER_GENERIC,
} from '../../constants/config';
import { DATE_FORMAT } from '../../constants/dateTimeFormats';
import { MAX_MOBILE_WIDTH, PAGE_INTRO, PAGE_PREFERENCES, PAGE_CANCELLED, PAGE_INFO, PAGE_DATE_SELECT, PAGE_CONFIRMED, PAGE_TOUR_PASSED, PAGE_TOUR_RESCHEDULE, PAGE_NEARBY_COMMUNITY } from '../../constants/formSections';
import { getIsConfirmationPage, getIsRescheduleFlow } from '../../utils/location';
import { parseAmenityValues } from '../../utils/choices';
import {
    createClientValidator,
    validatorFields,
    removeEmptyNestedObjects,
    isTourTypeFieldRequired
} from '../../utils/validators';

import Loading from './Loading';
import ServerErrorModal from './ServerErrorModal';
import * as appointmentUtils from '../../utils/appointment';

const { HIDDEN, REQUIRED } = EMPLOYEEGROUP_FIELD_CONFIG_CHOICES;
const RESCHEDULE_FLOW_FIELDS = ['time'];
const UpdatedMobileAppointmentScheduler = lazy(() => import('./UpdatedMobileAppointmentScheduler'));
const UpdatedDesktopAppointmentScheduler = lazy(() => import('./UpdatedDesktopAppointmentScheduler'));

export default class UpdatedAppointmentScheduler extends Component {
    constructor(props){
        super(props);
        this.state = {
            formData: {
                date: moment().format(DATE_FORMAT),
                time: null,
                appointment: {
                    broker_booked: false,
                    tour_type: undefined,
                    platform_of_choice: '',
                    platform_of_choice_details: '',
                },
                client: {
                    amenities: [],
                    layout: [],
                    pets: [],
                    move_in_date: null,
                    price_ceiling: null,
                    other_occupants: null,
                    current_postal_code: null,

                    broker_first_name: null,
                    broker_last_name: null,
                    broker_phone: null,
                    broker_email: null,
                    broker_company: null
                }
            },
            showValidationErrors: false,
            formErrors: {},
            client: null,
            company: null,
            currentAppointment: null,
            unit: null,
            building: null,
            community: null,
            employeeGroup: null,
            hasLoaded: false,
            isSubmitting: false,
            responseErrors: null,
            theme: null,
            dateSelectorKey: 0, // used to force the date selector to remount if its data gets stale
            fieldConfig: {},
            nearbyCommunities: [],
            previousAppointment: null,
        };

        this.clearErrorResponse = this.clearErrorResponse.bind(this);
        this.submitAppointment = this.submitAppointment.bind(this);
        this.updateFormData = this.updateFormData.bind(this);
        this.updateFieldConfig = this.updateFieldConfig.bind(this);
        this.rescheduleAppointment = this.rescheduleAppointment.bind(this);
        this.cancelAppointment = this.cancelAppointment.bind(this);
        this.getDisableDateAndPreferences = this.getDisableDateAndPreferences.bind(this);
        this._validateData = this._validateData.bind(this);
            }

    componentDidMount(){
        this.fetchInfo();
    }

    fetchInfo(){
        return this.props.API.fetchInfo().then(async data => {

            const fieldConfig = { ...data.employee_group.field_config };

            const isRescheduleFlow = getIsRescheduleFlow();
            fieldConfig['appointment.tour_type'] = !isRescheduleFlow ? REQUIRED : HIDDEN;
            fieldConfig['appointment.platform_of_choice'] = HIDDEN;
            fieldConfig['appointment.platform_of_choice_details'] = HIDDEN;

            const formData = this._getInitialFormData(data);
            const formErrors = this._validateData(formData, fieldConfig);

            await this.setState({
                theme: {
                    accentColor: `#${data.employee_group.primary_color || UPDATED_DEFAULT_ACCENT_COLOR}`
                },
                client: data.client,
                company: data.company,
                currentAppointment: data.current_appointment,
                previousAppointment: data.previous_appointment,
                community: data.community,
                nearbyCommunities: data.nearby_communities,
                building: data.building,
                employeeGroup: data.employee_group,
                unit: data.unit,
                formErrors,
                formData,
                fieldConfig,
                hasLoaded: true
            });
        });
    }

    clearErrorResponse(){
        const { errorResponse: { type } } = this.state;
        this.setState({ errorResponse: null });
        if (type === ERROR_RESPONSE_TYPE_START) {
            this.setState((state) => ({
                dateSelectorKey: state.dateSelectorKey + 1
            }));
            this.updateFormData('time', null);
        }
    }

    updateFormData(field, newValue){
        return new Promise((resolve) => {
            this.setState((state) => {
                const newFormData = Object.assign({}, state.formData);
                set(newFormData, field, newValue);
                if (field === 'appointment.broker_booked' && newValue === false) {
                    set(newFormData, 'client.broker_first_name', '');
                    set(newFormData, 'client.broker_last_name', '');
                    set(newFormData, 'client.broker_phone', '');
                    set(newFormData, 'client.broker_email', '');
                    set(newFormData, 'client.broker_company', '');
                }

                const formErrors = this._validateData(newFormData, state.fieldConfig);

                return {
                    formErrors,
                    formData: newFormData
                };
            }, resolve);
        });
    }

    updateFieldConfig (newConfig) {
        this.setState({
            fieldConfig: {
                ...this.state.fieldConfig,
                ...newConfig
            }
        });
    };

    rescheduleAppointment(){
        const formErrors = pick(this.state.formErrors, RESCHEDULE_FLOW_FIELDS);
        if (!isEmpty(formErrors)) {
            this.setState({
                showValidationErrors: true
            });
            return Promise.reject();
        }

        this.setState({ isSubmitting: true });
        const formData = {
            appointment: {
                start: this._parseAppointmentStartDate()
            }
        };
        return this.props.API.rescheduleAppointment(formData).then((data) => {
            this.setState((state) => ({
                isSubmitting: false,
                currentAppointment: Object.assign({}, state.currentAppointment, data.appointment, { status: APPOINTMENT_STATUS_CONFIRMED }),
                client: Object.assign({}, state.client, data.client)
            }));
        }).catch(({ response }) => {
            this.setState({
                isSubmitting: false,
                errorResponse: this._parseErrorResponse(response)
            });
            return Promise.reject();
        });
    }


    submitAppointment(thirdPartySGT){
        const { formErrors, employeeGroup } = this.state;

        const validationErrors = thirdPartySGT
        ? omit(formErrors, ['time'])
        : formErrors;

        if (!isEmpty(validationErrors)) {
            this.setState({
                showValidationErrors: true
            });
            return Promise.reject();
        }

        this.setState({ isSubmitting: true });
        
        if (thirdPartySGT) {
            const clientData = this._formatClientPreferencesData();

            return this.props.API.editClientPreferences(clientData).then((data) => {
                this.setState((state) => ({
                    isSubmitting: false,
                    client: Object.assign({}, state.client, data.client)
                }), () => {
                    // Redirect to the self_guided_tour_url after the state update
                    window.location.href = employeeGroup.self_guided_tour_url;
                });
            }).catch(({ response }) => {
                this.setState({
                    isSubmitting: false,
                    errorResponse: this._parseErrorResponse(response)
                });
    
                return Promise.reject();
            });
        }

        return this.props.API.saveAppointment(this._formatAppointmentData()).then((data) => {
            this.setState((state) => ({
                isSubmitting: false,
                currentAppointment: Object.assign({}, state.currentAppointment, data.appointment, { status: APPOINTMENT_STATUS_CONFIRMED }),
                client: Object.assign({}, state.client, data.client)
            }));
        }).catch(({ response }) => {
            this.setState({
                isSubmitting: false,
                errorResponse: this._parseErrorResponse(response)
            });

            return Promise.reject();
        });
    }

    async cancelAppointment(){
        this.setState({ isSubmitting: true });
        try {
            await this.props.API.cancelAppointment();
            this.setState((state) => ({
                isSubmitting: false,
                currentAppointment: Object.assign({}, state.currentAppointment, { status: APPOINTMENT_STATUS_CANCELLED })
            }));
        } catch (e) {
            this.setState({
                isSubmitting: false,
                errorResponse: this._parseErrorResponse(e.response)
            });
        }
    }

    getDisableDateAndPreferences () {
        const { fieldConfig, formData } = this.state;
        const tourTypeIsRequired = isTourTypeFieldRequired(fieldConfig);
        const tourTypeIsRequiredButNotSelected = tourTypeIsRequired && !formData.appointment.tour_type;
        const tourTypeIsVideoButMissingExtraFields = formData.appointment.tour_type === 'video' && (
            formData.appointment.platform_of_choice === '' ||
            formData.appointment.platform_of_choice_details === ''
        );

        if (!tourTypeIsRequiredButNotSelected && !tourTypeIsVideoButMissingExtraFields) {
            return false;
        }

        return true;
    };

    _validateData(formData, fieldConfig){
        const validator = createClientValidator(fieldConfig, validatorFields(formData), {}, this.state.client);
        const formDataWithClientRecord = Object.assign(
            {},
            formData,
            { _props:
                { client: this.state.client }
            }
        );
        if (!formData.client.person) {
            // set values to empty strings to the form fields are populated and trigger validators.
            formData.client.person = { email: '', phone_1: '' };
        }
        const errors = validator(formDataWithClientRecord);
        removeEmptyNestedObjects(errors);

        return errors;
    }

    _parseAppointmentStartDate(){
        const [hour, minute] = this.state.formData.time.split(':');
        const start = moment(this.state.formData.date, 'YYYY-MM-DD').hours(hour).minutes(minute).seconds(0).milliseconds(0).format();
        return start;
    }

    _formatAppointmentData(){
        const start = this._parseAppointmentStartDate();


        let smsOptedInOverwrite = false;
        let keepOldClientPhoneAndOptOut = false;
        const phoneFormValue = get(this.state, 'formData.client.person.phone_1');
        if (!this.state.client.person.phone_1 && phoneFormValue) {
            smsOptedInOverwrite = SMS_OPT_IN_MARKETING_ENABLED;
        // we present the phone_1 field with disclaimer if client has phone number and opted out to give them the option to opt in to messages again
        } else if (this.state.client.person.phone_1 && this.state.client.sms_opted_in !== SMS_OPT_IN_MARKETING_ENABLED) {
            if (phoneFormValue) {
                // if they do enter a number, we overwrite that number on the client and update to marketing enabled
                smsOptedInOverwrite = SMS_OPT_IN_MARKETING_ENABLED;
            } else {
                //  if they don't enter a number we keep the existing number on the client received from the api
                keepOldClientPhoneAndOptOut = true;
            }
        }
        const client = Object.assign({}, this.state.formData.client, {
            pets: castArray(this.state.formData.client.pets).filter(val => val !== NONE),
        },  parseAmenityValues(this.state.formData.client.amenities));

        if (smsOptedInOverwrite) {
            client.sms_opted_in = smsOptedInOverwrite;
        }
        if (keepOldClientPhoneAndOptOut) {
            client.sms_opted_in = this.state.client.sms_opted_in;
            const phone_1 = this.state.client.person.phone_1;
            if (client.person) {
                client.person.phone_1 = phone_1;
            } else {
                client.person = { phone_1 };
            }
        }

        const appointment = {
            ...this.state.formData.appointment,
            start,
        };

        if (appointment.tour_type === 'video') {
            appointment.is_video_tour = true;
        } else {
            appointment.is_video_tour = false;
            appointment.platform_of_choice = '';
            appointment.platform_of_choice_details = '';
        }

        appointment.tour_type = this._formatAppointmentTourType();

        delete client.amenities;

        // do not allow submitting blank values for client phone or email if they already exist on the client
        if (client.person.phone_1 === '' ) {
            client.person.phone_1 = this.state.client.person.phone_1;
        }
        if (client.person.email === '' ) {
            client.person.email = this.state.client.person.email;
        }

        return {
            appointment,
            client
        };
    }

    _formatClientPreferencesData() {
        const client = Object.assign({}, this.state.formData.client, {
            pets: castArray(this.state.formData.client.pets).filter(val => val !== NONE),
        });

        // Delete the person key from the client object so that we do not overwrite the person data
        delete client.person;
    
        return client;
    }

    // Note: obtaining the availability require us to send the tour type in numbers.
    // However, posting an appointment does require us to send the tour type in string format.
    // So here you go.
    _formatAppointmentTourType = () => {
        const { appointment: { tour_type } } = this.state.formData;
        if (tour_type === 'video' || tour_type === APPOINTMENT_TOUR_TYPE_GUIDED) {
            return APPOINTMENT_TOUR_TYPE_GUIDED_TEXT_VALUE;
        } else if (tour_type === APPOINTMENT_TOUR_TYPE_SELF_GUIDED) {
            return APPOINTMENT_TOUR_TYPE_SELF_GUIDED_TEXT_VALUE;
        }
    };

    getOverlappingLayouts(client, group){
        // find the overlapping layout options between client.preferences.layout and employee_group.layout_options
        const clientLayouts = client?.preferences.layout || [];
        const groupLayouts = group?.layout_options || [];
        return groupLayouts.filter(layout => clientLayouts.includes(layout));
    }

    _getInitialValuesFromClient(client, group){
        const values = {
            'client.pets': client.preferences.pets,
            'client.current_postal_code': client.current_postal_code,
            'client.layout': this.getOverlappingLayouts(client, group),
            'client.amenities': this._parseAmenityValues(client),
            'client.price_ceiling': client.preferences.price_ceiling,
            'client.move_in_date': client.preferences.move_in_date,
            'client.other_occupants': client.other_occupants,
        };

        if (client.person && !client.person.first_name && !client.person.last_name) {
            Object.assign(values, {
                'client.person.first_name': client.person.first_name,
                'client.person.last_name': client.person.last_name,
                'client.person.email': client.person.email,
                'client.person.phone_1': client.person.phone_1
            });
        }

        return values;
    }

    _getInitialFormData(data) {
        const { previous_appointment } = data;
        const newFormData = cloneDeep(this.state.formData);
        const initialValuesFromClient = this._getInitialValuesFromClient(data.client, data.employee_group);
        each(initialValuesFromClient, (value, field) => {
            if (!isUndefined(value)) {
                set(newFormData, field, value);
            }
        });

        if (!newFormData.client.price_ceiling) {
            const priceCeiling = this._getDefaultBudget({
                fieldConfig: data.employee_group.field_config,
                unit: data.unit,
                building: data.building,
                community: data.community
            });

            newFormData.client.price_ceiling = priceCeiling;
        }

        const currentAppointment = data.current_appointment;
        const tourPassed = moment(currentAppointment?.start).isBefore(moment());
        const tourCancelled = currentAppointment?.status === APPOINTMENT_STATUS_CANCELLED;
        const isCurrentTourActive = currentAppointment && !tourPassed && !tourCancelled;

        const useExistingTourType = getIsRescheduleFlow() || getIsConfirmationPage() || isCurrentTourActive;
        let tourType = undefined;
        if (useExistingTourType) {
            const isVideoTour = appointmentUtils.getIsVideoTour(currentAppointment);
            tourType = isVideoTour ? 'video' : currentAppointment?.tour_type;
        }
        newFormData.appointment.tour_type = tourType;

        if (previous_appointment) {
            const nextStartDate = moment(previous_appointment.end).add(
                NEARBY_COMMUNITY_SCHEDULING_TIME_DELTA_IN_MINUTES_FROM_PREVIOUS_APPOINTMENT,
                'minutes'
            );
            newFormData.time = nextStartDate.format('HH:mm');
            newFormData.date = nextStartDate.format('YYYY-MM-DD');
            newFormData.appointment.prospect_notes = previous_appointment.prospect_notes;
        }

        return newFormData;
    }

    _getAllowedRoutes(){
        const { currentAppointment, formData } = this.state;

        if (currentAppointment) {
            const tourIsPassed = moment(currentAppointment.start).isBefore(moment());
            if (currentAppointment.status === APPOINTMENT_STATUS_CANCELLED) {
                return [PAGE_CANCELLED, PAGE_DATE_SELECT, PAGE_INFO, PAGE_INTRO, PAGE_PREFERENCES];
            } else if (tourIsPassed) {
                return [PAGE_TOUR_PASSED, PAGE_DATE_SELECT, PAGE_INFO, PAGE_INTRO, PAGE_PREFERENCES];
            } else  {
                return [PAGE_CONFIRMED, PAGE_TOUR_RESCHEDULE, PAGE_NEARBY_COMMUNITY];
            }
        } else {
            const routes = [PAGE_INTRO];

            if (formData.appointment.tour_type){
                routes.push(PAGE_DATE_SELECT, PAGE_PREFERENCES);
                

                if (formData.time){
                    routes.push(PAGE_PREFERENCES);
                }
            }

            return routes;
        }
    }

    _getDefaultBudget({ fieldConfig, unit, building, community }){
        let price = null;
        if(unit) {
            price = Number(unit.price);
        } else if(community) {
            price = Number(community.avg_rental_price);
        } else if(building) {
            price = Number(building.avg_rental_price);
        }

        if (fieldConfig['client.price_ceiling'] === HIDDEN) {
            return null;
        } else {
            for (let i = 0; i < BUDGET_CHOICES.length; i++) {
                if (BUDGET_CHOICES[i].value >= price) {
                    return BUDGET_CHOICES[i].value;
                }
            }

            return BUDGET_CHOICES[BUDGET_CHOICES.length - 1].value;
        }
    }

    _parseAmenityValues(client){
        const AMENITY_FIELDS = ['doorman', 'elevator', 'laundry', 'outdoor_space', 'parking'];

        if (!client || !client.preferences) {
            return {};
        }

        const values = reduce(AMENITY_FIELDS, (acc, fieldName) => {
            const fieldValues = get(client, ['preferences', fieldName]);
            if (!fieldValues) {
                return acc;
            }
            const newValues = castArray(fieldValues).map(val => formatAmenityField(fieldName, val));
            return acc.concat(newValues);
        }, []);

        return values;
    }

    _parseErrorResponse(response){
        let type = ERROR_RESPONSE_TYPE_OTHER;
        let message = null;

        if (response.status === 400) {
            const responseMessage = response.data.message;
            if (isObject(responseMessage) && responseMessage.start) {
                type = ERROR_RESPONSE_TYPE_START;
                message = castArray(responseMessage.start).join(', ');
            } else if (isString(responseMessage)) {
                message = responseMessage;
            }
        }

        return { type, message };
    }

    getLayoutOptions() {
        const { client, employeeGroup } = this.state;
        const groupLayouts = employeeGroup?.layout_options || [];

        const overlappingLayouts = this.getOverlappingLayouts(client, employeeGroup);
        if (overlappingLayouts.length > 0) {
            // if there is some overlap between the client's layout preferences and group layout options, only show those
            return overlappingLayouts;
        } else {
            // if there is no overlap, but the client has some layout preferences
            // or the client has no layout preferences,
            // show all layout options that the community offers
            return groupLayouts;
        }
    }

    render(){
        if (!this.state.hasLoaded) {
            return <Loading />;
        }

        const {  API, basename, mapboxToken, } = this.props;
        const { client, company, currentAppointment, previousAppointment, building, community, dateSelectorKey, employeeGroup, errorResponse, formData,
            formErrors, showValidationErrors, isSubmitting, theme, unit, fieldConfig, nearbyCommunities } = this.state;
        const { logo, self_guided_tour_provider, self_guided_tour_provider_name } = employeeGroup;
        const allowedRoutes = this._getAllowedRoutes();

        const thirdPartySGT = formData.appointment.tour_type === SELF_GUIDED_TOUR_OPTION_V3.value &&
            self_guided_tour_provider !== SELF_GUIDED_TOUR_PROVIDER_GENERIC && self_guided_tour_provider_name;

        const sharedProps = {
            API,
            allowedRoutes,
            cancelAppointment: this.cancelAppointment,
            dateSelectorKey: dateSelectorKey,
            client,
            company,
            employeeGroup,
            currentAppointment,
            previousAppointment,
            fieldConfig,
            formErrors,
            layoutOptions: this.getLayoutOptions(),
            logo,
            isSubmitting,
            unit,
            nearbyCommunities,

            // the building and community data should have exactly the same shape, and if there is a community
            // related to the SchedulerLink, we should always prefer that data. Passing either one to child components
            // as 'building' to avoid a significant renaming right now
            building: community || building,

            formData,
            mapboxToken,
            updateFormData: this.updateFormData,
            updateFieldConfig: this.updateFieldConfig,
            rescheduleAppointment: this.rescheduleAppointment,
            submitAppointment: this.submitAppointment,
            showValidationErrors,
            disableDateAndPreferences: this.getDisableDateAndPreferences(),
            basename,
        };

        return (
            <ThemeProvider theme={theme}>
                <Router basename={basename}>
                    <Fragment>
                        <Suspense fallback={<Loading />}>
                            <Route render={({ history }) => (
                                <Media query={`(max-width: ${MAX_MOBILE_WIDTH}px)`}>
                                    {matches =>
                                    matches ? (
                                        <UpdatedMobileAppointmentScheduler
                                        {...sharedProps}
                                        thirdPartySGT={thirdPartySGT}
                                        history={history}
                                        />
                                        ) : (
                                            <UpdatedDesktopAppointmentScheduler
                                            {...sharedProps}
                                            thirdPartySGT={thirdPartySGT}
                                            history={history}
                                            />
                                            )
                                            }
                                </Media>

                            )} />
                        </Suspense>
                        <ServerErrorModal
                            clearErrorResponse={this.clearErrorResponse}
                            errorResponse={errorResponse}
                        />
                    </Fragment>
                </Router>
            </ThemeProvider>
        );
    }
}

UpdatedAppointmentScheduler.propTypes = {
    API: PropTypes.object.isRequired,
    mapboxToken: PropTypes.string.isRequired,
    basename: PropTypes.string.isRequired,
};
