import PropTypes from 'prop-types';
import React, { Component, Suspense, lazy } from 'react';
import injectSheet from 'react-jss';
import { Route, Redirect } from 'react-router-dom';

import Logo from './Logo';
import AllowedRoute from './AllowedRoute';
import { parseNewSchedulingLink } from '../../utils/location';
import Loading from './Loading';

import { PAGE_INTRO, PAGE_INFO, PAGE_PREFERENCES, PAGE_DATE_SELECT, PAGE_CONFIRMED, PAGE_CANCELLED, PAGE_TOUR_PASSED, PAGE_TOUR_RESCHEDULE, PAGE_NEARBY_COMMUNITY } from '../../constants/formSections';

import styles from './styles/UpdatedMobileAppointmentScheduler';

const MobileScheduleTourConfirmation = lazy(() => import('./MobileScheduleTourConfirmation'));
const MobilePageClientInfo = lazy(() => import('./MobilePageClientInfo'));
const MobileScheduleTourIntro = lazy(() => import('./MobileScheduleTourIntro'));
const MobileScheduleTourSelectTime = lazy(() => import('./MobileScheduleTourSelectTime'));
const MobileScheduleTourPreferences = lazy(() => import('./MobileScheduleTourPreferences'));
const MobileRescheduleTour = lazy(() => import('./MobileRescheduleTour'));
const UpdatedPageCancelled = lazy(() => import('./UpdatedPageCancelled'));
const UpdatedPageTourPassed = lazy(() => import('./UpdatedPageTourPassed'));
const PageNearbyCommunity = lazy(() => import('./PageNearbyCommunity'));

export class UpdatedMobileAppointmentScheduler extends Component {
    constructor() {
        super();
        this.state = {
            isLoadingNewLink: false,
        };
        this.clearErrorResponse = this.clearErrorResponse.bind(this);
        this.selectTime = this.selectTime.bind(this);
        this.submitAppointment = this.submitAppointment.bind(this);
        this.rescheduleAppointment = this.rescheduleAppointment.bind(this);
    }

    clearErrorResponse() {
        this.props.clearErrorResponse();
        this.props.history.push(PAGE_INFO);
    }

    selectTime(time) {
        this.props.updateFormData('time', time);
    }

    rescheduleAppointment(time) {
        return this.props.updateFormData('time', time).then(() => {
            return this.props.rescheduleAppointment();
        }).then(() => {
            this.props.history.push(PAGE_CONFIRMED);
        }).catch(() => {

        });
    }

    submitAppointment(thirdPartySGT) {
        // will redirect to confirmation page on success because it will change props.allowedRoutes
        return this.props.submitAppointment(thirdPartySGT).catch(() => {

        });
    }

    startSchedulingFromNearbyCommunity = async id => {
        const { API, basename, } = this.props;
        this.setState({ isLoadingNewLink: true });
        const { scheduler_link } = await API.createSchedulingLink({
            community: id,
        });
        this.setState({ isLoadingNewLink: false });
        location.replace(parseNewSchedulingLink(basename, scheduler_link));
    }

    handleIntroOnNext = () => {
        const { thirdPartySGT, history } = this.props;

        if (thirdPartySGT) {
            history.push(PAGE_PREFERENCES);
        } else {
            history.push(PAGE_DATE_SELECT);
        }
    };

    handlePreferencesBack = () => {
        const { thirdPartySGT, history } = this.props;

        if (thirdPartySGT) {
            history.push(PAGE_INTRO);
        } else {
            history.push(PAGE_DATE_SELECT);
        }
    };

    render() {
        const {
            allowedRoutes,
            API,
            building,
            cancelAppointment,
            classes,
            client,
            company,
            employeeGroup,
            currentAppointment,
            previousAppointment,
            dateSelectorKey,
            fieldConfig,
            formErrors,
            formData,
            isSubmitting,
            layoutOptions,
            unit,
            updateFormData,
            updateFieldConfig,
            mapboxToken,
            logo,
            showValidationErrors,
            disableDateAndPreferences,
            nearbyCommunities,
            thirdPartySGT,
        } = this.props;

        const { isLoadingNewLink } = this.state;

        return (
            <div className={classes.appointmentScheduler}>
                <div className={classes.mobileContent}>
                    <Suspense fallback={<Loading />}>
                        <Route exact path="/" render={() => (
                            <Redirect to={allowedRoutes[0]} />
                        )} />
                        <AllowedRoute allowedRoutes={allowedRoutes} path={PAGE_INTRO} render={({ location }) => (
                            <MobileScheduleTourIntro
                                building={building}
                                classes={classes}
                                location={location}
                                employeeGroup={employeeGroup}
                                mapboxToken={mapboxToken}
                                previousAppointment={previousAppointment}
                                updateFormData={updateFormData}
                                formData={formData}
                                fieldConfig={fieldConfig}
                                showValidationErrors={showValidationErrors}
                                formErrors={formErrors}
                                updateFieldConfig={updateFieldConfig}
                                onNext={() => this.handleIntroOnNext()}
                            />
                        )} />
                        <AllowedRoute allowedRoutes={allowedRoutes} path={PAGE_DATE_SELECT} render={({ history, location }) => (
                            <MobileScheduleTourSelectTime
                                building={building}
                                API={API}
                                fieldConfig={fieldConfig}
                                formErrors={formErrors}
                                formData={formData}
                                mapboxToken={mapboxToken}
                                disableDateAndPreferences={disableDateAndPreferences}
                                updateFormData={updateFormData}
                                selectTime={this.selectTime}
                                showValidationErrors={showValidationErrors}
                                key={dateSelectorKey}
                                location={location}
                                dateSelectorKey={dateSelectorKey}
                                employeeGroup={employeeGroup}
                                onNext={() => history.push(PAGE_PREFERENCES)}
                                onClickBack={() => history.push(PAGE_INTRO)}
                                maxDaysAhead={company.max_days_in_advance_to_book_tours}
                            />
                        )} />
                        <AllowedRoute allowedRoutes={allowedRoutes} path={PAGE_PREFERENCES} render={() => (
                            <MobileScheduleTourPreferences
                                building={building}
                                API={API}
                                fieldConfig={fieldConfig}
                                formErrors={formErrors}
                                formData={formData}
                                mapboxToken={mapboxToken}
                                disableDateAndPreferences={disableDateAndPreferences}
                                updateFormData={updateFormData}
                                selectTime={this.selectTime}
                                showValidationErrors={showValidationErrors}
                                key={dateSelectorKey}
                                location={location}
                                dateSelectorKey={dateSelectorKey}
                                employeeGroup={employeeGroup}
                                isSubmitting={isSubmitting}
                                company={company}
                                onNext={() => this.submitAppointment(thirdPartySGT)}
                                client={client}
                                layoutOptions={layoutOptions}
                                thirdPartySGT={thirdPartySGT}
                                onClickBack={() => this.handlePreferencesBack()}
                            />
                        )} />
                        <AllowedRoute allowedRoutes={allowedRoutes} path={PAGE_TOUR_RESCHEDULE} render={({ location }) => (
                            <MobileRescheduleTour
                                API={API}
                                building={building}
                                dateSelectorKey={dateSelectorKey}
                                unit={unit}
                                location={location}
                                formData={formData}
                                updateFormData={updateFormData}
                                rescheduleAppointment={this.rescheduleAppointment}
                                mapboxToken={mapboxToken}
                                isSubmitting={isSubmitting}
                                maxDaysAhead={company.max_days_in_advance_to_book_tours}
                            />
                        )} />
                        <AllowedRoute allowedRoutes={allowedRoutes} path={PAGE_INFO} render={({ location }) => (
                            formData.time ?
                                <MobilePageClientInfo
                                    building={building}
                                    company={company}
                                    clearErrorResponse={this.clearErrorResponse}
                                    isSubmitting={isSubmitting}
                                    fieldConfig={fieldConfig}
                                    formErrors={formErrors}
                                    location={location}
                                    client={client}
                                    updateFormData={updateFormData}
                                    formData={formData}
                                    layoutOptions={layoutOptions}
                                    logo={logo}
                                    unit={unit}
                                    showValidationErrors={showValidationErrors}
                                    submitAppointment={this.submitAppointment}
                                /> :
                                <Redirect to={PAGE_DATE_SELECT} />
                        )} />
                        <AllowedRoute allowedRoutes={allowedRoutes} path={PAGE_CONFIRMED} render={({ location }) => (
                            <MobileScheduleTourConfirmation
                                appointment={currentAppointment}
                                building={building}
                                cancelAppointment={cancelAppointment}
                                client={client}
                                isSubmitting={isSubmitting}
                                location={location}
                                logo={logo}
                                mapboxToken={mapboxToken}
                                unit={unit}
                                nearbyCommunities={nearbyCommunities}
                                formData={formData}
                            />
                        )} />
                        <AllowedRoute allowedRoutes={allowedRoutes} path={PAGE_CANCELLED} render={({ history }) => (
                            <UpdatedPageCancelled onClick={() => history.push(PAGE_INTRO)} />
                        )} />
                        <AllowedRoute allowedRoutes={allowedRoutes} path={PAGE_TOUR_PASSED} render={() => (
                            <UpdatedPageTourPassed />
                        )} />
                        <AllowedRoute allowedRoutes={allowedRoutes} path={PAGE_NEARBY_COMMUNITY} render={({ match, location, }) => (
                            <PageNearbyCommunity
                                isLoadingNewLink={isLoadingNewLink}
                                match={match}
                                location={location}
                                mapboxToken={mapboxToken}
                                referenceAddress={`${building.street_address}, ${building.city}, ${building.state} ${building.postal_code}`}
                                onSchedulingFromNearbyCommunity={this.startSchedulingFromNearbyCommunity}
                                API={API}
                            />
                        )} />
                    </Suspense>
                </div>
                <Logo className={classes.logo} logo={logo} />
            </div>
        );
    }
}

UpdatedMobileAppointmentScheduler.propTypes = {
    allowedRoutes: PropTypes.array.isRequired,
    API: PropTypes.object.isRequired,
    client: PropTypes.object,
    building: PropTypes.object.isRequired,
    cancelAppointment: PropTypes.func.isRequired,
    classes: PropTypes.object.isRequired,
    clearErrorResponse: PropTypes.func,
    client: PropTypes.object,
    company: PropTypes.object,
    employeeGroup: PropTypes.object,
    currentAppointment: PropTypes.object,
    previousAppointment: PropTypes.object,
    dateSelectorKey: PropTypes.number,
    fieldConfig: PropTypes.object.isRequired,
    formErrors: PropTypes.object.isRequired,
    layoutOptions: PropTypes.array.isRequired,
    history: PropTypes.object.isRequired,
    isSubmitting: PropTypes.bool.isRequired,
    unit: PropTypes.object,
    logo: PropTypes.string.isRequired,
    updateFormData: PropTypes.func.isRequired,
    updateFieldConfig: PropTypes.func.isRequired,
    formData: PropTypes.object.isRequired,
    mapboxToken: PropTypes.string.isRequired,
    submitAppointment: PropTypes.func.isRequired,
    showValidationErrors: PropTypes.bool.isRequired,
    rescheduleAppointment: PropTypes.func.isRequired,
    disableDateAndPreferences: PropTypes.bool.isRequired,
    nearbyCommunities: PropTypes.array,
    isDevEnv: PropTypes.bool,
    basename: PropTypes.string,
    thirdPartySGT: PropTypes.bool,
};

export default injectSheet(styles)(UpdatedMobileAppointmentScheduler);
