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

import Logo from './Logo';
import AllowedRoute from './AllowedRoute';
import { parseNewSchedulingLink } from '../../utils/location';
import styles from './styles/UpdatedDesktopAppointmentScheduler';
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';

const DesktopScheduleTourConfirmed = lazy(() => import('./DesktopScheduleTourConfirmed'));
const DesktopRescheduleTour = lazy(() => import('./DesktopRescheduleTour'));
const DesktopScheduleTourIntro = lazy(() => import('./DesktopScheduleTourIntro'));
const DesktopScheduleTourSelectTime = lazy(() => import('./DesktopScheduleTourSelectTime'));
const DesktopScheduleTourPreferences = lazy(() => import('./DesktopScheduleTourPreferences'));
const UpdatedPageCancelled = lazy(() => import('./UpdatedPageCancelled'));
const UpdatedPageTourPassed = lazy(() => import('./UpdatedPageTourPassed'));
const PageNearbyCommunity = lazy(() => import('./PageNearbyCommunity'));

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

    }

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

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

        });
    }

    rescheduleAppointment() {
        return this.props.rescheduleAppointment().then(() => {
            this.props.history.push(PAGE_CONFIRMED);
        }).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,
            cancelAppointment,
            company,
            employeeGroup,
            currentAppointment,
            previousAppointment,
            building,
            classes,
            client,
            dateSelectorKey,
            fieldConfig,
            formErrors,
            unit,
            layoutOptions,
            logo,
            isSubmitting,
            showValidationErrors,
            formData,
            mapboxToken,
            updateFormData,
            updateFieldConfig,
            disableDateAndPreferences,
            nearbyCommunities,
            thirdPartySGT,
        } = this.props;

        const { isLoadingNewLink } = this.state;

        return (
            <div className={classes.container}>
                <div className={classes.content}>
                    <Suspense fallback={<Loading />}>
                        <Route exact path="/" render={() => (
                            <Redirect to={allowedRoutes[0]} />
                        )} />
                        <AllowedRoute allowedRoutes={allowedRoutes} path={PAGE_INTRO} render={({ location }) => (
                            <DesktopScheduleTourIntro
                                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 }) => (
                            <DesktopScheduleTourSelectTime
                                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={() => (
                            <DesktopScheduleTourPreferences
                                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={() => this.submitAppointment(thirdPartySGT)}
                                client={client}
                                isSubmitting={isSubmitting}
                                company={company}
                                layoutOptions={layoutOptions}
                                thirdPartySGT={thirdPartySGT}
                                onClickBack={() => this.handlePreferencesBack()}
                            />
                        )} />
                        <AllowedRoute allowedRoutes={allowedRoutes} path={PAGE_TOUR_RESCHEDULE} render={({ location }) => (
                            <DesktopRescheduleTour
                                API={API}
                                building={building}
                                dateSelectorKey={dateSelectorKey}
                                formData={formData}
                                formErrors={formErrors}
                                fieldConfig={fieldConfig}
                                isSubmitting={isSubmitting}
                                location={location}
                                unit={unit}
                                logo={logo}
                                mapboxToken={mapboxToken}
                                rescheduleAppointment={this.rescheduleAppointment}
                                updateFormData={updateFormData}
                                selectTime={this.selectTime}
                                showValidationErrors={showValidationErrors}
                                maxDaysAhead={company.max_days_in_advance_to_book_tours}
                            />
                        )} />
                        <AllowedRoute allowedRoutes={allowedRoutes} path={PAGE_CONFIRMED} render={() => (
                            <DesktopScheduleTourConfirmed
                                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 />
                        )} />
                        <Route path={PAGE_INFO} render={() => (
                            <Redirect to={allowedRoutes[0]} />
                        )} />
                        <AllowedRoute allowedRoutes={allowedRoutes} path={PAGE_NEARBY_COMMUNITY} render={({ match, location, }) => (
                            <PageNearbyCommunity
                                isLoadingNewLink={isLoadingNewLink}
                                match={match}
                                location={location}
                                isDesktop={true}
                                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>
        );
    }
}

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

export default injectSheet(styles)(UpdatedDesktopAppointmentScheduler);
