import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import Grid from '@material-ui/core/Grid';
import cloneDeep from 'lodash/cloneDeep';
import { t } from 'Framework/i18n';

const styles = theme => ({
    Grid: {
        [theme.breakpoints.up('sm')]: {
            paddingRight: theme.spacing(2),
        },
    },
    MuiFormControlRoot: {
        marginTop: 0,
    },
    outlinedInput: {
        padding: 10,
        fontSize: 15,
        [theme.breakpoints.down('xs')]: {
            padding: 19,
        },
    },
    outlinedLabel: {
        fontSize: 15,
    },
});

const getErrorMessage = error => {
    return error ? t(error) : null;
};

const validateTextInput = (name, value) => {
    const emailRegexp = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i;

    if (value === '') {
        return 'receiveOfferForm.errors.required';
    }

    if (name === 'email' && !emailRegexp.test(value)) {
        return 'receiveOfferForm.errors.invalidEmail';
    }

    return null;
};

class ReceiveOfferForm extends React.Component {
    static propTypes = {
        classes: PropTypes.object,
    };

    constructor(props) {
        super(props);

        this.state = {
            email: {
                value: '',
                error: null,
            },
            name: {
                value: '',
                error: null,
            },
            company: {
                value: '',
                error: null,
            },
            phonenumber: {
                value: '',
                error: null,
            },
            zip: {
                value: '',
                error: null,
            },
            city: {
                value: '',
                error: null,
            },
            street: {
                value: '',
                error: null,
            },
            country: {
                value: '',
                error: null,
            },
        };
        this.inputRefs = {};
        this.handleChange = this.handleChange.bind(this);
        this.handleBlur = this.handleBlur.bind(this);
        this.setInputRef = this.setInputRef.bind(this);
    }

    setInputRef = ref => {
        if (ref) {
            this.inputRefs[ref.name] = ref;
        }
    };

    handleChange(event) {
        this.setState({
            [event.target.name]: {
                value: event.target.type === 'checkbox' ? event.target.checked : event.target.value,
                error: null,
            },
        });
    }

    handleBlur(event) {
        const value = cloneDeep(this.state[event.target.name]);

        value.error = validateTextInput(event.target.name, event.target.value);

        this.setState({
            [event.target.name]: value,
        });
    }

    validate() {
        let formErrors = false;
        let approvalNotSet = null;
        const values = {};

        const state = cloneDeep(this.state);

        const inputFields = ['email', 'name', 'company', 'phonenumber', 'zip', 'city', 'street', 'country'];

        let errorInputRef = null;
        for (const inputField of inputFields) {
            values[inputField] = state[inputField].value;

            const error = validateTextInput(inputField, state[inputField].value);

            if (error !== null) {
                formErrors = true;
            }

            if (error && !errorInputRef) {
                errorInputRef = this.inputRefs[inputField];
            }

            state[inputField].error = error;
        }

        this.setState(state);
        const hasError = formErrors || approvalNotSet === true;

        if (hasError) {
            const result = { hasError, formErrors };

            if (approvalNotSet !== null) {
                result.approvalNotSet = approvalNotSet;
            }

            return result;
        }

        return { hasError, ...values };
    }

    render() {
        const { classes } = this.props;

        const { email, name, company, phonenumber, zip, city, street, country } = this.state;

        return (
            <React.Fragment>
                <TextField
                    name="email"
                    inputRef={this.setInputRef}
                    value={email.value}
                    onChange={this.handleChange}
                    onBlur={this.handleBlur}
                    label={t('receiveOfferForm.email')}
                    margin="dense"
                    variant="outlined"
                    fullWidth
                    error={!!email.error}
                    helperText={getErrorMessage(email.error)}
                    InputProps={{
                        classes: {
                            input: classes.outlinedInput,
                        },
                    }}
                    InputLabelProps={{
                        classes: {
                            outlined: classes.outlinedLabel,
                        },
                    }}
                    classes={{
                        root: classes.MuiFormControlRoot,
                    }}
                />
                <TextField
                    name="name"
                    inputRef={this.setInputRef}
                    value={name.value}
                    onChange={this.handleChange}
                    onBlur={this.handleBlur}
                    label={t('receiveOfferForm.name')}
                    margin="dense"
                    variant="outlined"
                    translate="no"
                    fullWidth
                    error={!!name.error}
                    helperText={getErrorMessage(name.error)}
                    InputProps={{
                        classes: {
                            input: classes.outlinedInput,
                        },
                    }}
                    InputLabelProps={{
                        classes: {
                            outlined: classes.outlinedLabel,
                        },
                    }}
                />
                <TextField
                    name="company"
                    inputRef={this.setInputRef}
                    value={company.value}
                    onChange={this.handleChange}
                    onBlur={this.handleBlur}
                    label={t('receiveOfferForm.company')}
                    margin="dense"
                    variant="outlined"
                    translate="no"
                    fullWidth
                    error={!!company.error}
                    helperText={getErrorMessage(company.error)}
                    InputProps={{
                        classes: {
                            input: classes.outlinedInput,
                        },
                    }}
                    InputLabelProps={{
                        classes: {
                            outlined: classes.outlinedLabel,
                        },
                    }}
                />
                <TextField
                    name="phonenumber"
                    inputRef={this.setInputRef}
                    value={phonenumber.value}
                    onChange={this.handleChange}
                    onBlur={this.handleBlur}
                    label={t('receiveOfferForm.phonenumber')}
                    margin="dense"
                    variant="outlined"
                    fullWidth
                    error={!!phonenumber.error}
                    helperText={getErrorMessage(phonenumber.error)}
                    InputProps={{
                        classes: {
                            input: classes.outlinedInput,
                        },
                    }}
                    InputLabelProps={{
                        classes: {
                            outlined: classes.outlinedLabel,
                        },
                    }}
                />
                <Grid container>
                    <Grid item xs={12} sm={4} className={classes.Grid}>
                        <TextField
                            name="zip"
                            inputRef={this.setInputRef}
                            value={zip.value}
                            onChange={this.handleChange}
                            onBlur={this.handleBlur}
                            label={t('receiveOfferForm.zip')}
                            margin="dense"
                            variant="outlined"
                            fullWidth
                            error={!!zip.error}
                            helperText={getErrorMessage(zip.error)}
                            InputProps={{
                                classes: {
                                    input: classes.outlinedInput,
                                },
                            }}
                            InputLabelProps={{
                                classes: {
                                    outlined: classes.outlinedLabel,
                                },
                            }}
                        />
                    </Grid>
                    <Grid item xs={12} sm={8}>
                        <TextField
                            name="city"
                            inputRef={this.setInputRef}
                            value={city.value}
                            onChange={this.handleChange}
                            onBlur={this.handleBlur}
                            label={t('receiveOfferForm.city')}
                            margin="dense"
                            variant="outlined"
                            translate="no"
                            fullWidth
                            error={!!city.error}
                            helperText={getErrorMessage(city.error)}
                            InputProps={{
                                classes: {
                                    input: classes.outlinedInput,
                                },
                            }}
                            InputLabelProps={{
                                classes: {
                                    outlined: classes.outlinedLabel,
                                },
                            }}
                        />
                    </Grid>
                </Grid>
                <TextField
                    name="street"
                    inputRef={this.setInputRef}
                    value={street.value}
                    onChange={this.handleChange}
                    onBlur={this.handleBlur}
                    label={t('receiveOfferForm.street')}
                    margin="dense"
                    variant="outlined"
                    translate="no"
                    fullWidth
                    error={!!street.error}
                    helperText={getErrorMessage(street.error)}
                    InputProps={{
                        classes: {
                            input: classes.outlinedInput,
                        },
                    }}
                    InputLabelProps={{
                        classes: {
                            outlined: classes.outlinedLabel,
                        },
                    }}
                />
                <TextField
                    name="country"
                    inputRef={this.setInputRef}
                    value={country.value}
                    onChange={this.handleChange}
                    onBlur={this.handleBlur}
                    label={t('receiveOfferForm.country')}
                    margin="dense"
                    variant="outlined"
                    translate="no"
                    fullWidth
                    error={!!country.error}
                    helperText={getErrorMessage(country.error)}
                    InputProps={{
                        classes: {
                            input: classes.outlinedInput,
                        },
                    }}
                    InputLabelProps={{
                        classes: {
                            outlined: classes.outlinedLabel,
                        },
                    }}
                />
            </React.Fragment>
        );
    }
}

export default withStyles(styles, { name: 'ReceiveOfferForm' })(ReceiveOfferForm);
