import React, { useState, Component, Fragment } from 'react'
import { withStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import { Alert, AlertTitle } from '@material-ui/lab';
import Snackbar from '@material-ui/core/Snackbar';
import { connect } from 'react-redux'
import { updateUserRequest } from '../../actions/user'
import getConfig from 'next/config'
import Validator from "validator";
import AccountProfile from '../organisms/AccountProfile';
import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 } from 'react-html-parser';
import {
    Button,
} from '@material-ui/core';

const styles = theme => ({
    container: {
        width: '85%',
    },
    form: {
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '24px',
        paddingBottom: theme.spacing(8),
        marginBottom: theme.spacing(8),
        '&>div': {
            marginTop: theme.spacing(1.5),
            marginBottom: theme.spacing(1.5),
        }

    },
    textField: {
        width: '85%',
        '&:disabled': {
            color: theme.palette.secondary.dark,
        },
        '& label': {
            color: theme.palette.primary.dark,
        },
        '& fieldset:hover': {
            borderColor: theme.palette.primary.main + ' !important',
        },
    },
    textFieldSmall: {
        width: '48%',
        '&:disabled': {
            color: theme.palette.secondary.dark,
        },
        '& label': {
            color: theme.palette.primary.dark,
        },
        '& fieldset:hover': {
            borderColor: theme.palette.primary.main + ' !important',
        },
        padding: '5px',
    },
});

const { publicRuntimeConfig } = getConfig();

//https://xd.adobe.com/view/ba98331a-9145-4d67-7e27-25a36e519ef4-cca9/screen/a96779d7-bdb3-410a-8f19-e6987acb98ee/Candidature-Step-3
class AccountEtape1 extends Component {

    constructor(props) {
        super(props);
        
        // This binding is necessary to make `this` work in the callback
        this.handleChange = this.handleChange.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.onBlur = this.onBlur.bind(this)
        this.onSubmit = this.onSubmit.bind(this);
    }

    state = {
        file: null,
        firstname: '',
        lastname: '',
        email:'',
        phone: '',
        currentJob: '',
        address1:'',
        address2 : '',
        zipCode : '',
        city : '',
        country : '',
        linkedin: '',
        twitter: '',
        website: '',
        mediaId: null,
        companyId: null,
        
    };

    handleChange = (e) => {
        this.setState({ [e.target.name]: e.target.value });

        //console.log(this.refs.myTextField.input.value);
        //this.soumettre(e);
       
    }
    
    handleClose = (e, reason) => {
      
      if (reason === 'clickaway') {
        return;
      }
  
      //setOpen(false);
    };

    onBlur(e) {
        console.log("blur")
        this.setState({ [e.target.name]: e.target.value });
        
        this.soumettre(e.target.name, "unitaire");
      }     
    

    UNSAFE_componentWillReceiveProps(nextProps) {
        this.setState({
            firstname: nextProps.user.firstname,
            lastname: nextProps.user.lastname,
            phone: nextProps.user.phone,
            email: nextProps.user.email,
            currentJob: nextProps.user.currentJob,
            address1 : nextProps.user.address1,
            address2 : nextProps.user.address2,
            zipCode : nextProps.user.zipCode,
            city : nextProps.user.city,
            country : nextProps.user.country,
            linkedin: nextProps.user.linkedin,
            twitter: nextProps.user.twitter,
            website: nextProps.user.website,
            companyId: nextProps.companyId,
            errors: !!!nextProps.errors ? { errors: { message: "" } } : nextProps.errors,
        })
    }

    componentDidMount() {
        this.setState({
            firstname: this.props.user.firstname,
            lastname: this.props.user.lastname,
            phone: this.props.user.phone,
            email: this.props.user.email,
            address1: this.props.user.address1,
            address2 : this.props.user.address2,
            zipCode : this.props.user.zipCode,
            city : this.props.user.city,
            country : this.props.user.country,
            currentJob: this.props.user.currentJob,
            linkedin: this.props.user.linkedin,
            twitter: this.props.user.twitter,
            website: this.props.user.website,
        })
        
    }

    onSubmit = (e) => {
        
        e.preventDefault();
        console.log("submit")
        console.log(e.keyCode)
        
        this.soumettre(e.target.name, "global")
        
    }
    soumettre(champ, type){
        console.log("soumettre");
        console.log(champ);
        const errors = this.validate(this.state, champ, type);
        const success = {};
        this.setState({ errors });
        if (!this.state.errors || !this.state.errors.message){
            
            success.message ="Profil mis à jour";
            this.setState({ success });
            const data = new FormData()
            data.append('firstname', this.state.firstname)
            data.append('lastname', this.state.lastname)
            data.append('phone', this.state.phone)
            //data.append('email', this.state.email)
            data.append('currentJob', this.state.currentJob)
            data.append('address1', this.state.address1)
            data.append('address2', this.state.address2)
            data.append('zipCode', this.state.zipCode)
            data.append('city', this.state.city)
            data.append('country', this.state.country)
            data.append('linkedin', this.state.linkedin)
            data.append('twitter', this.state.twitter)
            data.append('website', this.state.website)
            
            //TODO:maybe add this two in a single transactionnal saga
            this.props.updateUserRequest(data) 
            
            
        }
    }
    validate(data,champ, type){
        console.log("valdiate")
        console.log(champ);
        const errors = {};
        errors.message ="";
        //if (!Validator.isEmail(data.currentJob)) errors.message += "Le poste actuel doit etre un email\n";
        if (type=="global" || (champ=="firstname" &&  data.firstname=="")) errors.message += "Veuillez saisir votre prénom<br />";
        if (type=="global" || (champ=="lastname" &&  data.lastname=="")) errors.message += " Veuillez saisir votre nom<br />";
        if (type=="global" || (champ=="phone" && data.phone=="")) errors.message += "Veuillez saisir un numéro de téléphone<br />";
        if (type=="global" || (champ=="currentJob" &&  data.currentJob=="")) errors.message += "Veuillez saisir votre intitulé de poste actuel ou poste recherché<br />";
        if (type=="global" || (champ=="zipCode" && (data.zipCode && data.zipCode!="") && !Validator.isPostalCode(data.zipCode, "FR"))) errors.message += "Le code postal n'est pas correct<br />";
        // if ((data.website && data.website!="") && !Validator.isURL(data.website)) errors.message += " Veuillez ajouter un site internet avec une url valide<br />";
         if (!Validator.isMobilePhone(data.phone, "fr-FR") && !Validator.isNumeric(data.phone, "fr-FR")) errors.message += "Le téléphone n'est pas correct<br />";
        //console.log(errors.email);
        
        return errors;
    };
    AfficherErreurs() {
        if (!this.state.errors || !this.state.errors.message){
            return "";
        }else if (this.state.errors.length != 0 && this.state.errors.message!="") {
            return (
            <Alert severity="error">
               { ReactHtmlParser(this.state.errors.message)} 
            </Alert>
            );
        }
        return ""; 
    }

    

    AfficherSuccess() {
    //   if (this.state.success && this.state.success.length != 0 && this.state.success.message != "") {      
    //       return (
    //         <Snackbar open={open} autoHideDuration={1000} onClose={() => this.setState({open: false})}>
    //           <Alert onClose={() => this.setState({open: false})} severity="success">
    //             {ReactHtmlParser(this.state.success.message)}
    //           </Alert>
    //         </Snackbar>
            
              
    //       );
        
    //   }
      return "";
    }

    

    inputFilesystemChange = (e) => {

        console.log("inputFilesystemChange");
        var file = e.target.files[0]
        this.setState({ picture: file })

        const data = new FormData()
        data.append('file', file)
        this.props.updateUserPictureRequest(data)
    }

    

    render() {
        const { classes, user } = this.props
        const logoUrl = user.picture;
        function refresh() {
            document
                .location
                .reload(true);
            
        }
        return (
          <section className={classes.container}>
            <form className={classes.form}
                    autoComplete="off" focused="true" name="monForm" ref="formToSubmit">
                    {/* {!!logoUrl && <Avatar className={classes.logo}
                        classes={{ img: classes.MuiAvatarImg }}
                        src={publicRuntimeConfig.symphonyUrl + publicRuntimeConfig.postedContentUrl + logoUrl} alt="candidatLogo" />} */}

                    {/* {!!user.pictureLoading && <Loader />}    
                    {!!!user.pictureLoading && !!!logoUrl &&
                        (<Fragment><input
                            type="file" accept="image/*" capture="filesystem"
                            className={classes.input}
                            style={{ display: 'none' }}
                            id="raised-button-file"
                            multiple
                            type="file"
                            onChange={this.inputFilesystemChange}
                        />
                            <label htmlFor="raised-button-file">
                                <Button component="span" className={classes.importButton} classes={{ root: classes.rootButton }}>
                                    <img alt="talents-tube" src='/static/images/default/account-avatar-default.svg'
                                        className={classes.iconButton} />
                                    <Typography align="left" className={classes.textButton}>
                                        J'<span className={classes.underlined}>importe</span> ma photo de profil
                                    </Typography>
                                    <KeyboardArrowRightIcon className={classes.InputKeyboardArrowRightIcon} />
                                </Button>
                            </label></Fragment>)
                    } */}
                    {this.AfficherErreurs()}
                    {this.AfficherSuccess()}
                    

                    <TextField
                        name="firstname"
                        required
                        id="outlined-required"
                        label="Prénom"
                        className={classes.textField}
                        classes={{ root: classes.rootTextfield }}
                        variant="outlined"
                        value={this.state.firstname}
                        onChange={this.handleChange}
                        onBlur={this.onBlur} 
                    />

                    <TextField
                        name="lastname"
                        required
                        id="outlined-required"
                        label="Nom"
                        className={classes.textField}
                        classes={{ root: classes.rootTextfield }}
                        variant="outlined"
                        value={this.state.lastname}
                        onChange={this.handleChange}
                        onBlur={this.onBlur} 
                    />

                    <TextField
                        disabled
                        name="email"
                        id="outlined"
                        label="E-mail"
                        required
                        className={classes.textField}
                        classes={{ root: classes.rootTextfield }}
                        variant="outlined"
                        value={this.state.email}
                        onChange={this.handleChange}
                        type="mail"
                        onBlur={this.onBlur} 
                    />

                    <TextField
                        name="phone"
                        id="outlined"
                        label="Téléphone"
                        required
                        className={classes.textField}
                        classes={{ root: classes.rootTextfield }}
                        variant="outlined"
                        value={this.state.phone ? this.state.phone: ''}
                        onChange={this.handleChange}
                        type="tel"
                        onBlur={this.onBlur} 
                    />

                    

                    <TextField
                        name="currentJob"
                        id="outlined"
                        label="Poste actuel"
                        required
                        className={classes.textField}
                        classes={{ root: classes.rootTextfield }}
                        variant="outlined"
                        value={this.state.currentJob =='null' || this.state.currentJob ==''  ? '' :this.state.currentJob}
                        onChange={this.handleChange}
                        onBlur={this.onBlur} 
                    />

                    <TextField
                        name="address1"
                        id="outlined"
                        label="Adresse"
                        className={classes.textField}
                        classes={{ root: classes.rootTextfield }}
                        variant="outlined"
                        value={this.state.address1 ? this.state.address1 : ''}
                        onChange={this.handleChange}
                        onBlur={this.onBlur} 
                    />

                    <TextField
                        name="address2"
                        id="outlined"
                        label="Adresse complémentaire"
                        className={classes.textField}
                        classes={{ root: classes.rootTextfield }}
                        variant="outlined"
                        value={this.state.address2 ? this.state.address2  : ''}
                        onChange={this.handleChange}
                        onBlur={this.onBlur} 
                    />    
                    <div className={classes.container}>
                    <TextField
                        name="zipCode"
                        id="outlined"
                        label="Code postal"
                        className={classes.textField}
                        classes={{ root: classes.textFieldSmall }}
                        variant="outlined"
                        value={this.state.zipCode ? this.state.zipCode : ''}
                        onChange={this.handleChange}
                        onBlur={this.onBlur} 
                    /> 

                    <TextField
                        name="city"
                        id="outlined"
                        label="Ville"
                        className={classes.textField}
                        classes={{ root: classes.textFieldSmall }}
                        variant="outlined"
                        value={this.state.city ? this.state.city : ''}
                        onChange={this.handleChange}
                        onBlur={this.onBlur} 
                    />      

                    <TextField
                        name="country"
                        id="outlined"
                        label="Pays"
                        className={classes.textField}
                        classes={{ root: classes.textFieldSmall }}
                        variant="outlined"
                        value={this.state.country ? this.state.country : ''}
                        onChange={this.handleChange}
                        onBlur={this.onBlur} 
                    />
                    </div>           

                    <TextField
                        name="linkedin"
                        id="outlined"
                        label="Linkedin"
                        className={classes.textField}
                        classes={{ root: classes.rootTextfield }}
                        variant="outlined"
                        placeholder="http://www.linkedin.com/in/"
                        value={this.state.linkedin =='null' || this.state.linkedin ==''  ? '' :this.state.linkedin}
                        onChange={this.handleChange}
                        onBlur={this.onBlur} 

                    />

                    <TextField
                        name="twitter"
                        id="outlined"
                        label="Twitter"
                        className={classes.textField}
                        classes={{ root: classes.rootTextfield }}
                        variant="outlined"
                        placeholder="http://twitter.com/.."
                        value={this.state.twitter =='null' || this.state.twitter ==''  ? '' :this.state.twitter}
                        onChange={this.handleChange}
                        onBlur={this.onBlur} 
                    />

                    <TextField
                        name="website"
                        id="outlined"
                        label="Site internet"
                        className={classes.textField}
                        classes={{ root: classes.rootTextfield }}
                        variant="outlined"
                        placeholder="http://monsite.fr"
                        value={this.state.website =='null' || this.state.website ==''  ? '' :this.state.website}
                        onChange={this.handleChange}
                        onBlur={this.onBlur} 
                    />
                    <Button
                            type="submit"
                            variant="contained"
                            color="primary"
                            
                            className={classes.button}>
                            Enregistrer
                        </Button>
                </form>
                {/* <div id="F" className={classes.foot}>
                    <Button variant="contained" className={classes.button + ' cypButtonSendApplication'} onClick={this.onSubmit}>Mettre à jour!</Button>
                </div> */}
            </section>
        )
    }
}

function mapStateToProps(state, ownProps) {
    return {
        user: state.user ,
        loading: !!state.user.loading,
        pictureLoading: !!state.user.pictureLoading,
        errors: state.user.errors || ownProps.errors,
        mediaId: state.media.message && state.media.message.mediaId,
    };
}

export default withStyles(styles)(connect(mapStateToProps, {  updateUserRequest })(AccountEtape1));
