import React, { Component, Fragment } from 'react'
import { withStyles } from '@material-ui/core/styles';
import { Button, Typography } from '@material-ui/core';
import TextField from '@material-ui/core/TextField';
import Input from '@material-ui/core/Input';
import { connect } from 'react-redux'
import { postAdAnswerRequest } from '../../actions/answer'
import { updateUserRequest, updateUserPictureRequest } from '../../actions/user'
import Avatar from '@material-ui/core/Avatar';
import KeyboardArrowRightIcon from '@material-ui/icons/KeyboardArrowRight';
import Loader from './../templates/loader'
import getConfig from 'next/config'

const styles = theme => ({
    container: {
        width: '100%',
    },
    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),
        },
        [theme.breakpoints.up('md')]: {
            padding: '0 calc(25vw + 24px)',
        },

    },
    importContainer: {
        alignSelf: 'flex-start',
    },
    textField: {
        width: '100%',
        '&:disabled': {
            color: theme.palette.secondary.dark,
        },
        '& label': {
            color: theme.palette.primary.dark,
        },
        '& fieldset:hover': {
            borderColor: theme.palette.primary.main + ' !important',
        },
    },
    foot: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: '10',
        width: '100%',
        position: 'fixed',
        bottom: 0,
        padding: theme.spacing(1.2, 0),
        backgroundColor: theme.palette.secondary.main,
        boxShadow: '0px 0px 10px rgba(30, 35, 39, 0.10)',
    },
    rootButton: {
        textTransform: 'inherit',
        border: '1px solid',
        '&:hover': {
            border: '1px solid',
        },
    },
    button: {
        textTransform: 'inherit',
        marginLeft: theme.spacing(8),
        marginRight: theme.spacing(8),
        padding: theme.spacing(1.2, 2),
        color: theme.palette.secondary.main,
        backgroundColor: theme.palette.primary.important,
    },

    importButton: {
        color: theme.palette.primary.main,
        backgroundColor: theme.palette.secondary.main,
        padding: theme.spacing(3, 2),
        margin: theme.spacing(1),
        boxShadow: '0 6px 10px 0 rgba(0, 0, 0, 0.14), 0 1px 18px 0 rgba(0, 0, 0, 0.12), 0 3px 5px -1px rgba(0, 0, 0, 0.14)',
        '&:hover': {
            backgroundColor: theme.palette.secondary.main,
        },
        InputKeyboardArrowRightIcon: {
            fontSize: '2.5em',
            color: theme.palette.secondary.main,
        },
    },
});

const { publicRuntimeConfig } = getConfig()
//https://xd.adobe.com/view/ba98331a-9145-4d67-7e27-25a36e519ef4-cca9/screen/a96779d7-bdb3-410a-8f19-e6987acb98ee/Candidature-Step-3
class Answer extends Component {

    constructor(props) {
        super(props);

        // This binding is necessary to make `this` work in the callback
        this.onSubmit = this.onSubmit.bind(this);
    }

    state = {
        file: null,
        firstname: '',
        lastname: '',
        phone: '',
        currentJob: '',
        linkedin: '',
        twitter: '',
        website: '',
        mediaId: null,
        companyId: null,
    };

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

    UNSAFE_componentWillReceiveProps(nextProps) {
        this.setState({
            firstname: nextProps.user.firstname,
            lastname: nextProps.user.lastname,
            phone: nextProps.user.phone,
            currentJob: nextProps.user.currentJob,
            linkedin: nextProps.user.linkedin,
            twitter: nextProps.user.twitter,
            website: nextProps.user.website,
            mediaId: nextProps.mediaId,
            companyId: nextProps.companyId,
        })
    }

    componentDidMount() {
        this.setState({
            firstname: this.props.user.firstname,
            lastname: this.props.user.lastname,
            phone: this.props.user.phone,
            currentJob: this.props.user.currentJob,
            linkedin: this.props.user.linkedin,
            twitter: this.props.user.twitter,
            website: this.props.user.website,
        })
    }

    onSubmit = (e) => {
        e.preventDefault()

        const data = new FormData()

        data.append('firstname', this.state.firstname)
        data.append('lastname', this.state.lastname)
        data.append('phone', this.state.phone)
        data.append('currentJob', this.state.currentJob)
        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)
        //TODO: faire appel à une méthode qui va encoyer le mail a l'entreprise 
        
        // this.props.companyMails.map((user) =>
        //     //TODO Envoyer un mail a chaque user
        //     console.log(user.email)
        // )
        this.props.postAdAnswerRequest(
            {
                adId: this.props.adId,
                companyId: this.props.companyId,
                mediaId: this.props.mediaId
            })
    }

    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;
        return (
            <section className={classes.container}>
                <form className={classes.form}
                    autoComplete="off">
                    {!!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>)
                    }
                    <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}
                    />

                    <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}
                    />

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

                    <TextField
                        disabled
                        id="outlined-required"
                        label="E-mail"
                        className={classes.textField}
                        classes={{ root: classes.rootTextfield }}
                        variant="outlined"
                        value={user.email}
                    />

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

                    <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}
                        onChange={this.handleChange}

                    />

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

                    <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}
                        onChange={this.handleChange}
                    />
                </form>
                <div id="F" className={classes.foot}>
                <Button variant="contained" className={classes.button + ' cypButtonSendApplication'} onClick={this.onSubmit}>Envoyer ma candidature</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, { postAdAnswerRequest, updateUserRequest, updateUserPictureRequest })(Answer))