import PropTypes from 'prop-types';
import React from 'react';
import moment from 'moment';
import classnames from 'classnames';
import FieldError from './FieldError';
import { ISO_FORMAT, TIME_FORMAT_DISPLAY, DATE_FORMAT_DISPLAY_FULL } from '../../constants/dateTimeFormats';
import { SELECT_APPOINTMENT } from '../../constants/formSections';

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

        this.editAppointmentTime = this.editAppointmentTime.bind(this);
    }

    editAppointmentTime (e) {
        e.preventDefault();
        this.props.serializeAndSetFormData();
        this.props.setFormSection(SELECT_APPOINTMENT);
    }

    render () {
        const { appointment, errors } = this.props;

        const appointmentStart = moment(appointment.start, ISO_FORMAT);
        const formattedDate = appointmentStart.format(DATE_FORMAT_DISPLAY_FULL);
        const formattedTime = appointmentStart.format(TIME_FORMAT_DISPLAY);
        const locationText = appointment.location && <AppointmentLocation location={appointment.location} />;

        return (
            <div>
                <div>
                    Appointment on <strong>{formattedDate}</strong> at <strong>{formattedTime}</strong>{locationText}
                    {' '}
                    <a href="#" className="cheryl__button-link" onClick={this.editAppointmentTime}>Edit Appointment</a>
                </div>
                <div className={classnames('cheryl__field-group', { cheryl__error: errors && Object.keys(errors).length })}>
                    {errors && Object.keys(errors).map(fieldName => {
                        return (
                            <FieldError
                                key={fieldName}
                                error={errors[fieldName]}
                                style={{ marginLeft: 0 }}
                            />
                        );
                    })}
                </div>
            </div>
        );
    }
}

AppointmentDetails.propTypes = {
    appointment: PropTypes.shape({
        start: PropTypes.string,
        expiration_date: PropTypes.string,
        location: PropTypes.string,
    }).isRequired,
    setFormSection: PropTypes.func.isRequired,
    serializeAndSetFormData: PropTypes.func.isRequired,
    errors: PropTypes.object,
};

export const AppointmentLocation = props => <span> at <strong>{props.location}</strong></span>;

AppointmentLocation.propTypes = {
    location: PropTypes.string.isRequired,
};
