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

import Loading from './Loading';
import BuildingMap from './BuildingMap';
import PhotoCarousel from './PhotoCarousel';
import styles from './styles/PageNearbyCommunity';
import LocationPin from './Svg/LocationPin';

export class PageNearbyCommunity extends React.Component {
    constructor() {
        super();
        this.state = {
            isLoading: true,
            isShowingFullAbout: false,
            isShowingFullCommunityFeatures: false,
            isShowingFullApartmentFeatures: false,
            about: '',
            name: null,
            officeHours: [],
            buildingName: null,
            unitNumber: null,
            amenities: [],
            apartmentFeatures: [],
            availableLayouts: [],
            phone: null,
            distance: null,
            website: null,
            photos: [],
            location: null,
            streetAddress: null,
        };
    }

    async componentDidMount() {
        const { match, API } = this.props;
        const { communityId } = match.params;
        const {
            name,
            distance,
            photos,
            location,
            building_name,
            lowest_priced_unit,
            available_layouts,
            amenities,
            apartment_features,
            description,
            contact_phone,
            website_url,
            hours_of_operation,
            street_address,
        } = await API.fetchNearbyCommunityData(communityId);

        this.setState({
            isLoading: false,
            name: name,
            about: description,
            officeHours: hours_of_operation,
            buildingName: building_name,
            unitNumber: lowest_priced_unit?.unit_number,
            amenities: amenities,
            apartmentFeatures: apartment_features,
            availableLayouts: available_layouts,
            phone: contact_phone,
            distance: distance,
            website: website_url,
            photos: photos,
            location: location,
            streetAddress: street_address,
        });
    }

    normalizeWeekDay = day => {
        return day[0].toUpperCase() + day.slice(1, 3);
    }

    normalizeTime = time => {
        return moment(time, 'HH:mm:ss').format('hA');
    }

    toggleShowMoreAbout = () => {
        this.setState({ isShowingFullAbout: !this.state.isShowingFullAbout });
    }

    toggleShowMoreCommunityFeatures = () => {
        this.setState({ isShowingFullCommunityFeatures: !this.state.isShowingFullCommunityFeatures });
    }

    toggleShowMoreApartmentFeatures = () => {
        this.setState({ isShowingFullApartmentFeatures: !this.state.isShowingFullApartmentFeatures });
    }

    renderLabelComponent = () => {
        const { classes, referenceAddress } = this.props;
        const { distance, name } = this.state;
        return (
            <div className={classes.labelSection}>
                <h3>
                    {name}
                </h3>
                <p>
                    <LocationPin className={classes.locationIcon} />
                    <span>{pluralize('mile', distance, true)} away</span> from {referenceAddress}
                </p>
            </div>
        );
    }

    renderCommunityFeatures = (showMore = false) => {
        const { classes, } = this.props;
        const { amenities, } = this.state;
        return amenities.slice(showMore ? 6 : 0, showMore ? amenities.length : 6).map((feature, idx) => (
            <li key={idx} className={classes.feature}>
                {feature}
            </li>
        ));
    }

    renderApartmentFeatures = (showMore = false) => {
        const { classes, } = this.props;
        const { apartmentFeatures, } = this.state;
        return apartmentFeatures.slice(showMore ? 6 : 0, showMore ? apartmentFeatures.length : 6).map((feature, idx) => (
            <li key={idx} className={classes.feature}>
                {feature}
            </li>
        ));
    }

    renderShowMoreOrLessButton = (showingMore = false, handler) => {
        const { classes } = this.props;
        return (
            <div className={classes.showMore} onClick={handler}>
                {showingMore ? 'Show less' : 'Show more'}
            </div>
        );
    }

    renderCommunityAbout = () => {
        const { isDesktop, } = this.props;
        const { about, } = this.state;
        const ellipis = ((isDesktop && about.length > 600) || (!isDesktop && about.length > 255)) ? '...' : '';
        return this.state.isShowingFullAbout ? about : about.substr(0, isDesktop ? 600 : 255).concat(ellipis);
    }

    renderOfficeHours = () => {
        const { officeHours, } = this.state;
        return Object.keys(officeHours).map((day, idx) => !officeHours[day].is_closed
            &&
            <Fragment key={idx}>
                {this.normalizeWeekDay(day)}: {this.normalizeTime(officeHours[day].open_at)}-{this.normalizeTime(officeHours[day].close_at)}<br />
            </Fragment>
        );
    }

    renderWebsiteAddress = () => {
        const { website, } = this.state;
        if (website.startsWith('http://') || website.startsWith('https://')) {
            return website;
        }
        return 'http://'.concat(website);
    }

    render() {
        const { isShowingFullAbout, isShowingFullCommunityFeatures, isShowingFullApartmentFeatures } = this.state;
        const { classes, match, mapboxToken, onSchedulingFromNearbyCommunity, isLoadingNewLink, isDesktop, } = this.props;
        const { communityId } = match.params;
        const {
            buildingName,
            unitNumber,
            amenities,
            apartmentFeatures,
            phone,
            website,
            photos,
            location,
            streetAddress,
            about,
        } = this.state;

        const shouldShowMoreAbout = (isDesktop && about.length > 600) || (!isDesktop && about.length > 255);

        if (this.state.isLoading) {
            return (
                <div className={classes.loadingContainer}>
                    <Loading />
                </div>
            );
        }
        return (
            <div className={classes.container}>
                <PhotoCarousel
                    buildingName={buildingName}
                    photos={photos}
                    publicAddress={streetAddress}
                    unitNumber={unitNumber}
                    lightboxEnabled
                    isNearbyCommunityFlow
                    labelComponent={this.renderLabelComponent}
                />
                <div className={classnames(classes.info, !this.state.about.length && classes.centeredInfo)}>
                    {!!this.state.about.length && (
                        <div className={classes.about}>
                            <h5 className={classes.title}>About the Community</h5>
                            {this.renderCommunityAbout()}
                            {shouldShowMoreAbout && this.renderShowMoreOrLessButton(isShowingFullAbout, this.toggleShowMoreAbout)}
                        </div>
                    )}
                    <div className={classes.sections}>
                        <div className={classes.section}>
                            {!!Object.keys(this.state.officeHours).length && (
                                <div className={classes.hours}>
                                    <h5 className={classes.title}>Office Hours</h5>
                                    {this.renderOfficeHours()}
                                </div>
                            )}
                            <div className={classes.contactContainer}>
                                <div className={classes.contact}>
                                    {!!this.state.phone.length && (
                                        <>
                                            <h5 className={classes.title}>Phone Number</h5>
                                            {phone}
                                        </>
                                    )}
                                    {!!this.state.website.length && (
                                        <>
                                            <h5 className={classes.title}>Website</h5>
                                            <a href={this.renderWebsiteAddress()} target="_blank">{website}</a>
                                        </>
                                    )}
                                </div>
                            </div>
                        </div>
                        <div className={classes.sectionBlock}>
                            {!!amenities?.length &&
                                <div className={classes.section}>
                                    <div className={classes.features}>
                                        <h5 className={classes.title}>Community Features</h5>
                                        <ul className={classes.featureList}>
                                            {this.renderCommunityFeatures()}
                                        </ul>
                                        {isShowingFullCommunityFeatures && <ul className={classes.featureList}>
                                            {this.renderCommunityFeatures(true)}
                                        </ul>}
                                        {amenities.length > 6 && this.renderShowMoreOrLessButton(isShowingFullCommunityFeatures, this.toggleShowMoreCommunityFeatures)}
                                    </div>
                                </div>
                            }
                            {!!apartmentFeatures?.length &&
                                <div className={classes.section}>
                                    <div className={classes.features}>
                                        <h5 className={classes.title}>Apartment Features</h5>
                                        <ul className={classes.featureList}>
                                            {this.renderApartmentFeatures()}
                                        </ul>
                                        {isShowingFullApartmentFeatures && <ul className={classes.featureList}>
                                            {this.renderApartmentFeatures(true)}
                                        </ul>}
                                        {apartmentFeatures.length > 6 && this.renderShowMoreOrLessButton(isShowingFullApartmentFeatures, this.toggleShowMoreApartmentFeatures)}
                                    </div>
                                </div>
                            }
                        </div>
                    </div>
                </div>
                {location &&
                    <div className={classes.mapBox}>
                        <BuildingMap
                            center={location}
                            fullScreenOnClick={false}
                            mapboxToken={mapboxToken}
                            publicAddress={streetAddress}
                            location={location}
                            zoom={14}
                            appointment={{}}
                        />
                    </div>
                }
                <button className={classes.scheduleButton} onClick={() => onSchedulingFromNearbyCommunity(communityId)}>
                    {isLoadingNewLink ? 'Loading ...' : 'Schedule a Tour'}
                </button>
            </div>
        );
    }
}

PageNearbyCommunity.propTypes = {
    match: PropTypes.object,
    classes: PropTypes.object,
    onSchedulingFromNearbyCommunity: PropTypes.func,
    location: PropTypes.object,
    isDesktop: PropTypes.bool,
    isLoadingNewLink: PropTypes.bool,
    mapboxToken: PropTypes.string,
    API: PropTypes.object,
    referenceAddress: PropTypes.string,
};

export default injectSheet(styles)(PageNearbyCommunity);
