import PropTypes from 'prop-types';
import React from 'react';
import serialize from 'form-serialize';
import isEmpty from 'lodash/isEmpty';
import moment from 'moment';

import { jss } from '../../utils/styles';
import { createClientValidator, validatorFields } from '../../utils/validators';
import { saveAppointment, saveClient } from '../../utils/api';
import { parseAmenityValues } from '../../utils/choices';
import { createStyles } from './styles/ClientInformation';

import {
    AMENITY_CHOICES,
    APPOINTMENT_TOUR_TYPE_SELF_GUIDED_TEXT_VALUE,
    EMPLOYEEGROUP_FIELD_CONFIG_CHOICES,
    NONE,
    PET_CHOICES,
    SMS_OPT_IN_MARKETING_ENABLED,
    WIDGET_TYPE_LEAD_CAPTURE,
    WIDGET_TYPE_LEAD_CAPTURE_APPOINTMENT,
    WIDGET_TYPE_SAVE_BUTTON_TEXT,
    WIDGET_TYPES,
} from '../../constants/config';
import { APPOINTMENT_CONFIRMED, CONFIRMATION, FIND_APPOINTMENT } from '../../constants/formSections';
import { DATE_FORMAT_INPUT_DISPLAY, ISO_FORMAT } from '../../constants/dateTimeFormats';

import { InputCalendarSelect, InputMultiSelect, InputSingleSelect } from './InputSelect';
import Input from './Input';
import FormHeader from './FormHeader';
import InputWrapper from './InputWrapper';
import BrokerInformation from './BrokerInformation';
import AppointmentDetails from './AppointmentDetails';
import NeighborhoodsSelect from './NeighborhoodsSelect';
import SMSDisclaimer from './SMSDisclaimer';
import FormErrorsAriaNotification from './FormErrorsAriaNotification';
import FieldGroup from './FieldGroup';
import { renderPreferredTourTypeSelectLabel } from './FindAppointment';

const { REQUIRED, HIDDEN } = EMPLOYEEGROUP_FIELD_CONFIG_CHOICES;

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

        const moveInDate = props.initialValues.client.move_in_date;

        this.state = {
            submitting: false,
            isBroker: false,
            data: {
                move_in_date: moveInDate ? moment(moveInDate) : null,
                layout: props.initialValues.client.layout,
                pets: props.initialValues.client.pets,
                discovery_source: props.initialValues.client.discovery_source,
                amenities: props.initialValues.client.amenities,
                neighborhoods: props.initialValues.client.neighborhoods,
                lead_source: props.initialValues.client.lead_source,
            },
            errors: {},
        };

        this.handleSubmit = this.handleSubmit.bind(this);
        this.bindChangeHandler = this.bindChangeHandler.bind(this);
        this.isBrokerHandler = this.isBrokerHandler.bind(this);
        this.cleanData = this.cleanData.bind(this);
        this.serializeAndSetFormData = this.serializeAndSetFormData.bind(this);
        this.serialize = this.serialize.bind(this);
        this.setTourType = this.setTourType.bind(this);
    }

    componentWillMount () {
        this.stylesheet = jss.createStyleSheet(createStyles(this.context.customColor), { named: false });
        this.stylesheet.attach();
    }

    componentWillUnmount () {
        this.stylesheet.detach();
    }

    serialize (formNode) {
        const serialized = serialize(formNode, { hash: true, empty: true });
        serialized.client.layout = !serialized.client.layout || serialized.client.layout[0] === '' ? null : serialized.client.layout[0].split(',');
        serialized.client.pets = !serialized.client.pets || serialized.client.pets[0] === '' ? null : serialized.client.pets[0].split(',');
        if (serialized.client.people[0].phone_1) {
            serialized.client.sms_opted_in = SMS_OPT_IN_MARKETING_ENABLED;
        }

        serialized.client.neighborhoods = this.state.data.neighborhoods;

        if (serialized.client.amenities && serialized.client.amenities[0] !== '') {
            const amenities = serialized.client.amenities[0].split(',');
            const amenityValues = parseAmenityValues(amenities);
            Object.assign(serialized.client, amenityValues);
        } else {
            serialized.client.amenities = null;
        }
        if (this.props.communityId) {
            serialized.client.community = this.props.communityId;
        }
        if (this.props.unitId) {
            serialized.client.unit = this.props.unitId;
        }

        serialized.client.discovery_source = parseInt(serialized.client.discovery_source);
        serialized.client.lead_source = parseInt(serialized.client.lead_source);

        return serialized;
    }

    validate (formData) {
        const { config, employeeGroup } = this.props;
        return createClientValidator(config, validatorFields(formData), { employeeGroup })(formData);
    }

    handleSubmit (e) {
        e.preventDefault();
        const data = this.serialize(e.target);
        const errors = this.cleanErrors(this.validate(data));
        const cleanedData = this.cleanData(data);

        if (isEmpty(errors)) {
            this.save(cleanedData);
        }
        else {
            this.setState({ errors });
        }
    }

    cleanData (data) {
        data.appointment = data.appointment || {};

        if (this.context.widgetType === WIDGET_TYPE_LEAD_CAPTURE_APPOINTMENT) {
            data.appointment.broker_booked = data.appointment.broker_booked === 'on';
            if (this.props.isThirdPartySelfGuidedTour) {
                data.appointment.tour_provider = this.props.employeeGroup?.self_guided_tour_provider;
            }
            data.appointment = Object.assign({}, this.props.appointment, data.appointment);
        } else {
            delete data.appointment;
        }

        data.client.move_in_date = data.client.move_in_date ? moment(data.client.move_in_date, DATE_FORMAT_INPUT_DISPLAY).format(ISO_FORMAT) : null;
        // data.client.neighborhoods = this.state.data.neighborhoods;
        delete(data.client.amenities);

        if (this.state.data.pets === NONE) {
            delete(data.client.pets);
        }
        if (data.client.neighborhoods == null)
            delete(data.client.neighborhoods);

        return data;
    }

    cleanErrors (errors) {
        if (errors.client.people && isEmpty(errors.client.people[0])) {
            delete errors.client.people;

            if (isEmpty(errors.client)) {
                delete errors.client;
            }
        }

        return errors;
    }

    getWidgetTypeSave () {
        const widgetTypes = {
            [WIDGET_TYPE_LEAD_CAPTURE]: saveClient,
            [WIDGET_TYPE_LEAD_CAPTURE_APPOINTMENT]: saveAppointment,
        };

        return widgetTypes[this.context.widgetType];
    }

    save (data) {
        const save = this.getWidgetTypeSave();

        this.setState({
            submitting: true,
        });

        const client = Object.assign(
            {}, data.client,
            this.context.campaignInfo ? { campaign_info: this.context.campaignInfo } : {},
            this.context.leadSource ? { lead_source: this.context.leadSource } : {}, // TODO dont override set leadsource
        );

        const params = Object.assign(
            {},
            data,
            { client },
            this.context.originSource ? { origin_source: this.context.originSource } : {},
        );

        return save(params)
            .then(response => {
                if (this.props.isThirdPartySelfGuidedTour) {
                    // redirect to third party booking page after saving the lead
                    this.props.onNavigate(this.props.employeeGroup?.self_guided_tour_url);
                }
                this.props.setFormData(Object.assign({}, data, response.body.data));
                let formSection = CONFIRMATION;
                if(this.context.widgetType === WIDGET_TYPE_LEAD_CAPTURE_APPOINTMENT && ! response.body.data.appointment.confirmation_enabled) {
                    // If this is an appointment widget, and the group does not have 'appointment confirmation enabled' turned on, the appointment
                    // is auto-confirmed, so just show them a thank you screen.
                    formSection = APPOINTMENT_CONFIRMED;
                }
                this.props.setFormSection(formSection);
                this.props.onComplete();
            })
            .catch(errorResponse => {
                const errors = errorResponse.response.body.errors;
                this.setState({
                    submitting: false,
                    errors
                });
            });
    }

    isBrokerHandler (e) {
        this.setState({
            isBroker: !!e.target.checked
        });
    }

    bindChangeHandler (fieldName) {
        return val => {
            if (Array.isArray(val) && val.includes(NONE)) {
                this.setState({
                    data: Object.assign({}, this.state.data, {
                        [fieldName]: NONE
                    })
                });
            } else {
                this.setState({
                    data: Object.assign({}, this.state.data, {
                        [fieldName]: val
                    })
                });
            }
        };
    }

    serializeAndSetFormData () {
        const data = this.cleanData(this.serialize(this.form));

        this.props.setFormData(data);
    }

    setTourType = (val) => {
        // If the user unselects the self-guided tour option,
        // we should reset the form section to the find appointment section
        const appointment = {
            ...this.props.appointment,
            tour_type: val
        };

        this.props.setFormData({ appointment });
        if (val !== APPOINTMENT_TOUR_TYPE_SELF_GUIDED_TEXT_VALUE) {
            this.props.setFormSection(FIND_APPOINTMENT);
        }
    };

    render() {
        const { errors: fieldErrors, data, isBroker } = this.state;
        const {
            appointment,
            setFormSection,
            initialValues,
            config,
            managementCompanyName,
            isThirdPartySelfGuidedTour
        } = this.props;
        const isAppointmentWidget = this.context.widgetType === WIDGET_TYPE_LEAD_CAPTURE_APPOINTMENT;
        const errors = fieldErrors.client || {};
        let submitBtnLabel = this.context.customSubmitBtnLabel || WIDGET_TYPE_SAVE_BUTTON_TEXT[this.context.widgetType];
        if (isThirdPartySelfGuidedTour) {
            const label = this.props.employeeGroup?.self_guided_tour_provider_name;
            submitBtnLabel = `Book tour with ${label}`;
        }
        const selectLabels = {
            DESIRED_NEIGHBORHOODS: 'Desired neighborhoods',
            DESIRED_AMENITIES: 'Desired amenities',
            LAYOUT: 'Layout',
            DO_YOU_HAVE_PETS: 'Do you have any pets?',
            HEAR_ABOUT_US: 'How did you hear about us?',
            LEAD_SOURCE: 'Lead Source'
        };

        return (
            <form ref={node => this.form = node} onSubmit={this.handleSubmit}>
                <FormHeader>
                    {isAppointmentWidget && !isThirdPartySelfGuidedTour && (
                        <AppointmentDetails
                            appointment={appointment}
                            setFormSection={setFormSection}
                            serializeAndSetFormData={this.serializeAndSetFormData}
                            errors={fieldErrors.appointment}
                        />
                    )}
                </FormHeader>

                <FormErrorsAriaNotification errors={errors}/>
                {isThirdPartySelfGuidedTour && (<div className="cheryl__row">
                        <FieldGroup
                            labelText="Preferred Tour Type"
                            containerClassName="cheryl__select-tour-type"
                        >
                            <InputSingleSelect
                                ariaLabel="Tour Type"
                                placeholder="Select tour type"
                                value={appointment?.tour_type}
                                options={this.props.tourTypeOptions}
                                onChange={this.setTourType}
                                renderOptionLabel={renderPreferredTourTypeSelectLabel}
                            />
                        </FieldGroup>
                    </div>)}

                <div className="cheryl__row cheryl__form-options">
                    {
                        config['client.broker_toggle'] !== HIDDEN &&
                        <div className="cheryl__checkbox cheryl__broker-checkbox">
                            <label htmlFor="is-broker">
                                <input
                                    id="is-broker"
                                    type="checkbox"
                                    name="appointment[broker_booked]"
                                    onChange={this.isBrokerHandler}
                                    defaultValue={initialValues.appointment.broker_booked}
                                /> I&rsquo;m a Broker
                            </label>
                        </div>
                    }
                </div>

                {isBroker && <BrokerInformation errors={errors} config={config}/>}

                <div className="cheryl__row">
                    <Input
                        name="client[people][0][first_name]"
                        labelText="First Name"
                        containerClassName="cheryl__col-1-2"
                        error={errors.people && errors.people[0].first_name}
                        defaultValue={initialValues.client.people[0].first_name}
                        required
                    />
                    <Input
                        name="client[people][0][last_name]"
                        labelText="Last Name"
                        containerClassName="cheryl__col-1-2"
                        error={errors.people && errors.people[0].last_name}
                        defaultValue={initialValues.client.people[0].last_name}
                        required
                    />
                </div>

                <div className="cheryl__row" style={{ marginBottom: 0 }}>
                    <Input
                        name="client[people][0][email]"
                        labelText="Email"
                        error={errors.people && errors.people[0].email}
                        defaultValue={initialValues.client.people[0].email}
                        containerClassName="cheryl__col-1-2 neighborhoods"
                        required
                    />

                    <Input
                        name="client[people][0][phone_1]"
                        labelText="Phone Number"
                        containerClassName="cheryl__col-1-2 neighborhoods"
                        error={errors.people && errors.people[0].phone_1}
                        defaultValue={initialValues.client.people[0].phone_1}
                    />
                </div>

                <div className="cheryl__row">
                    <SMSDisclaimer submitBtnLabel={submitBtnLabel} managementCompanyName={managementCompanyName} />
                </div>
                <div className="cheryl__row">
                    <InputWrapper
                        required={config['client.neighborhoods'] === REQUIRED}
                        hidden={config['client.neighborhoods'] === HIDDEN}
                        labelText={selectLabels.DESIRED_NEIGHBORHOODS}
                        containerClassName="cheryl__col-1-2 neighborhoods"
                        error={errors.neighborhoods}
                    >
                        <NeighborhoodsSelect
                            ariaLabel={selectLabels.DESIRED_NEIGHBORHOODS}
                            inputName="client[neighborhoods][]"
                            options={this.props.neighborhoodOptions}
                            value={data.neighborhoods}
                            onChange={this.bindChangeHandler('neighborhoods')}
                        />
                    </InputWrapper>

                    <InputWrapper
                        required={config['client.amenities'] === REQUIRED}
                        hidden={config['client.amenities'] === HIDDEN}
                        labelText={selectLabels.DESIRED_AMENITIES}
                        containerClassName="cheryl__col-1-2"
                        error={errors.amenities}
                    >
                        <InputMultiSelect
                            ariaLabel={selectLabels.DESIRED_AMENITIES}
                            inputName="client[amenities][]"
                            value={data.amenities}
                            placeholder="Select amenities"
                            options={AMENITY_CHOICES}
                        />
                    </InputWrapper>
                </div>

                <div className="cheryl__row">
                    <InputWrapper
                        required={config['client.move_in_date'] === REQUIRED}
                        hidden={config['client.move_in_date'] === HIDDEN}
                        labelText="Move in date"
                        containerClassName="cheryl__col-1-2"
                        error={errors.move_in_date}
                    >
                        <InputCalendarSelect
                            inputName="client[move_in_date]"
                            placeholder="Select date"
                            value={data.move_in_date}
                            onChange={this.bindChangeHandler('move_in_date')}
                            defaultValue={data.move_in_date || null}
                            ariaHidden={true}
                        />
                    </InputWrapper>

                    <InputWrapper
                        required={config['client.layout'] === REQUIRED}
                        hidden={config['client.layout'] === HIDDEN}
                        labelText={selectLabels.LAYOUT}
                        containerClassName="cheryl__col-1-2"
                        error={errors.layout}
                    >
                        <InputMultiSelect
                            ariaLabel={selectLabels.LAYOUT}
                            inputName="client[layout][]"
                            value={data.layout}
                            placeholder="Select layout"
                            onChange={this.bindChangeHandler('layout')}
                            options={this.props.layoutOptions}
                        />
                    </InputWrapper>
                </div>

                <div className="cheryl__row">
                    <Input
                        name="client[price_floor]"
                        labelText="Min Price"
                        containerClassName="cheryl__col-1-2"
                        error={errors.price_floor}
                        defaultValue={initialValues.client.price_floor}
                        required={config['client.price_floor'] === REQUIRED}
                        hidden={config['client.price_floor'] === HIDDEN}
                    />
                    <Input
                        name="client[price_ceiling]"
                        labelText="Max Price"
                        containerClassName="cheryl__col-1-2"
                        error={errors.price_ceiling}
                        defaultValue={initialValues.client.price_ceiling}
                        required={config['client.price_ceiling'] === REQUIRED}
                        hidden={config['client.price_ceiling'] === HIDDEN}
                    />
                </div>

                <div className="cheryl__row">
                    <InputWrapper
                        required={config['client.pets'] === REQUIRED}
                        hidden={config['client.pets'] === HIDDEN}
                        labelText={selectLabels.DO_YOU_HAVE_PETS}
                        containerClassName="cheryl__col-1-2"
                        error={errors.pets}
                    >
                        {data.pets === NONE ? (
                            <InputSingleSelect
                                ariaLabel={selectLabels.DO_YOU_HAVE_PETS}
                                inputName="client[pets][]"
                                value="SELECT-OPTION-NO-VALUE"
                                placeholder="Select pets"
                                onChange={this.bindChangeHandler('pets')}
                                options={PET_CHOICES}
                            />
                        ) : (
                            <InputMultiSelect
                                ariaLabel={selectLabels.DO_YOU_HAVE_PETS}
                                inputName="client[pets][]"
                                value={data.pets}
                                placeholder="Select pets"
                                onChange={this.bindChangeHandler('pets')}
                                options={PET_CHOICES}
                            />
                        )}
                    </InputWrapper>

                    <InputWrapper
                        required={config['client.disabled_source'] === REQUIRED}
                        hidden={config['client.discovery_source'] === HIDDEN}
                        labelText={selectLabels.HEAR_ABOUT_US}
                        containerClassName="cheryl__col-1-2 referral"
                        error={errors.discovery_source}
                    >
                        <InputSingleSelect
                            ariaLabel={selectLabels.HEAR_ABOUT_US}
                            inputName="client[discovery_source]"
                            value={data.discovery_source}
                            placeholder="Select one"
                            onChange={this.bindChangeHandler('discovery_source')}
                            options={this.props.discoverySourceChoices}
                        />
                    </InputWrapper>
                </div>

                <div className="cheryl__row">
                    <InputWrapper
                        required={config['client.lead_source'] === REQUIRED}
                        hidden={config['client.lead_source'] === HIDDEN || !this.context.leadSourceEnabled}
                        labelText={selectLabels.LEAD_SOURCE}
                        containerClassName="cheryl__col-1-2 referral"
                        error={errors.lead_source}
                    >
                        <InputSingleSelect
                            ariaLabel={selectLabels.HEAR_ABOUT_US}
                            inputName="client[lead_source]"
                            value={data.lead_source}
                            placeholder="Select one"
                            onChange={this.bindChangeHandler('lead_source')}
                            options={this.props.discoverySourceChoices}
                        />
                    </InputWrapper>
                </div>

                <div className="cheryl__row">
                    <InputWrapper
                        required={config['client.notes'] === REQUIRED}
                        hidden={config['client.notes'] === HIDDEN}
                        labelText="Notes"
                        containerClassName=""
                        error={errors.notes}
                    >
                        <div className="cheryl__field-group">
                            <textarea name="client[notes]" className="cheryl__field" rows="10" defaultValue={initialValues.client.notes}></textarea>
                        </div>
                    </InputWrapper>
                </div>

                <div>
                    <button className="cheryl__button-primary" disabled={this.state.submitting}>
                        {submitBtnLabel}
                    </button>
                </div>
            </form>
        );
    }
}

ClientInformation.defaultProps = {
    config: {}
};

ClientInformation.propTypes = {
    neighborhoodOptions: PropTypes.array.isRequired,
    setFormSection: PropTypes.func.isRequired,
    discoverySourceChoices: PropTypes.array.isRequired,
    setFormData: PropTypes.func.isRequired,
    config: PropTypes.object.isRequired,
    appointment: PropTypes.shape({
        start: PropTypes.string,
        expiration_date: PropTypes.string,
        location: PropTypes.string,
    }),
    employeeGroup: PropTypes.object.isRequired,
    initialValues: PropTypes.object.isRequired,
    layoutOptions: PropTypes.array.isRequired,
    communityId: PropTypes.number,
    unitId: PropTypes.number,
    onComplete: PropTypes.func.isRequired,
    managementCompanyName: PropTypes.string.isRequired,
    isThirdPartySelfGuidedTour: PropTypes.bool,
    tourTypeOptions: PropTypes.array,
    onNavigate: PropTypes.func,
};

ClientInformation.contextTypes = {
    widgetType: PropTypes.oneOf(WIDGET_TYPES).isRequired,
    customColor: PropTypes.string,
    customSubmitBtnLabel: PropTypes.string,
    groupId: PropTypes.number,
    campaignInfo: PropTypes.string,
    originSource: PropTypes.string,
    leadSourceEnabled: PropTypes.bool,
    leadSource: PropTypes.number,
};
