import React, { Fragment } from 'react';
import { connect } from "react-redux";
import { fetchCurrentUserRequest } from '../../actions/user'
import { fetchCompanyRequest } from '../../actions/companies'
import { uploadMediaCv } from '../../actions/mediaCv'
import { withStyles } from '@material-ui/core/styles'
import { makeStyles } from '@material-ui/styles';
import { Button, Typography, Divider, Hidden } from '@material-ui/core';
import KeyboardArrowRightIcon from '@material-ui/icons/KeyboardArrowRight';
import KeyboardArrowDownIcon from '@material-ui/icons/KeyboardArrowDown';
import LoaderVideo from '../../components/templates/loaderVideo'
import Snack from '../../components/atoms/snack';
import Snackbar from '@material-ui/core/Snackbar';
import { Alert, AlertTitle } from '@material-ui/lab';
import ReactHtmlParser from 'react-html-parser';
import getConfig from 'next/config'
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';


const styles = theme => ({
  root: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'flex-start',
    margin: theme.spacing(1),
  },
  rootButton: {
    textTransform: 'inherit',
  },
  underlined: {
    textDecoration: 'underline',
  },
  textButton: {
    fontWeight: '700',
    fontSize: '1.15em',
    paddingLeft: theme.spacing(2),
  },
  InputKeyboardArrowDownIcon: {
    fontSize: '2.5em',
    color: theme.palette.primary.main,
  },
  importButton: {
    color: theme.palette.primary.main,
    backgroundColor:  theme.palette.secondary.main,
    padding: theme.spacing(3, 2),
    margin: theme.spacing(1),
    width: "370px",
    boxShadow: '0 6px 10px 0 rgba(0, 0, 0, 0.14), 0 1px 18px 0 rgba(0, 0, 0, 0.12), 0 3px 5px -1' +
            'px rgba(0, 0, 0, 0.14)',
    '&:hover': {
        color: theme.palette.primary.main,
        backgroundColor:  theme.palette.secondary.main,
    }
  },
});


const { publicRuntimeConfig } = getConfig();
class Etape3 extends React.Component {
  state = {
    loading: true,
    openSnack: false,
    cv:false,
    errors: {},
    success : {}
  };

  componentDidMount() {
    localStorage.setItem('loginRedirect', window.location.pathname)

    if(!!!localStorage.getItem('ttJWT'))
    {
      Router.push("/Login")
    }
    else
      this.setState({
        loading: false,
        cvLink: this.props.user.cv
      })
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    
    this.setState({
        cvLink: nextProps.cvLink,
        loading: nextProps.loading,
        openSnack: !!!_.isEmpty(nextProps.errors),
        errors: !!!nextProps.errors ? { errors: { message: "" } } : nextProps.errors,
    })
    this.state.cvLink = nextProps.cvLink;
    if (nextProps.loading) {
      const success = {};
      success.message ="CV mis à jour";
      console.log("CV mis à jour!!!")
      if(this.state.cvLink) console.log(this.state.cvLink)
      this.setState({ success });
      
    }

    
  }

  inputFilesystemChange = (e) => {
    this.uploadMediaCv(e)
  }
  
  uploadMediaCv = (e) => {
    var file = e.target.files[0]

    const data = new FormData()
    data.append('upload', file)

    this.props.uploadMediaCv(data)
  }

  AfficherSuccess() {
    if (!this.state.success || !this.state.success.message) {
        console.log("Erreur Upload CV");
        return "";
    } else if (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 "";
  }

  AfficherLienCv() {
    console.log("afficher lien");
     if (this.state.cvLink !="") {
      
        return (
          
          <Fragment>
            <Hidden>&nbsp;</Hidden>
            <Hidden>&nbsp;</Hidden>
            
            <Hidden>&nbsp;</Hidden>
            <Hidden>&nbsp;</Hidden>
            <Card  variant="" style={{
              width:370+"px", 
              boxShadow: '0 6px 10px 0 rgba(0, 0, 0, 0.14), 0 1px 18px 0 rgba(0, 0, 0, 0.12), 0 3px 5px -1' +
                      'px rgba(0, 0, 0, 0.14)',
              marginLeft : '10px',
              marginTop:'10px'
              
              }}>
            <Hidden>&nbsp;</Hidden>
              <CardActions>
                <Button size="small">MON CV</Button>
              </CardActions>
              <CardContent>
                <Typography >
                  <a href={publicRuntimeConfig.symphonyUrl + publicRuntimeConfig.postedContentCv + this.state.cvLink} 
                  target="_blank"
                  style={{ 
                    color:'#1689FB',
                    '&:hover': {
                      color: '#1689FB',
                    },
                    fontWeight: '700',
                    fontSize: '1em',
                    }}
                  >
                    Visualiser mon CV
                    </a>
                    <br />
                {/* <a href="https://www.permatheque.fr/PDF/mansobufukuoka-larevolutiondunseulbrindepaille.pdf" target="_blank">lien</a> */}
                </Typography>
              </CardContent>
              
            </Card>
          </Fragment>
            
        );
      
    }
    return "";
  }

  render() {
    const { classes, company } = this.props;
    const { loading } = this.state;
    return (
      <Fragment>
      { loading ? 
        <LoaderVideo textePrincipal="Votre candidature vidéo est en cours d’envoi..." texteSecondaire="Veuillez rester sur la page pendant le chargement qui peut durer plusieurs minutes."/> :
        <Fragment>
          {this.AfficherSuccess()}
          
          <input
            type="file" 
            accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document, .pdf, .odt"
            className={classes.input+' cypButtonImportVid'}
            style={{ display: 'none' }}
            id="import-button-file"
            onChange={this.inputFilesystemChange}
          />
          <label htmlFor="import-button-file">
            <Button component="span" className={classes.importButton} classes={{ root: classes.rootButton }}>
              <img alt="talents-tube" src='/statique/images/Import-cv-candidat.svg' className={classes.iconButton} />
              <Typography  className={classes.textButton}>
                J'<span className={classes.underlined}>importe</span> mon CV 
              </Typography>
              <KeyboardArrowDownIcon className={ classes. InputKeyboardArrowDownIcon }/>
            </Button>
            
          </label>
          <Hidden>&nbsp;</Hidden>
          {this.AfficherLienCv()}
          
        </Fragment>
    }
    </Fragment>
    ); 
  }

}

Etape3.getInitialProps = function (context) {

  const { adId, companyId } = context.query
  const {res} = context
    //TODO :really needed ?
     context.store.dispatch(fetchCurrentUserRequest())

  if(!!adId)
    context.store.dispatch(fetchJobRequest(adId))
  else if(!!companyId)
    context.store.dispatch(fetchCompanyRequest(companyId))

    return {};//leave this please
}

function mapStateToProps(state) {
  // console.log("mapStateToProps")
  // console.log(state.loading)
  // console.log(state.user)
  // console.log(state.media.message)
  return {
    user: state.user ,
    cvLink : state.mediaCv.message,
    loading: !!state.media.loading,
    cv : true,
    //errors:  errorMessageSelector(state),
    user: state.user,
    company: state.company
  };
}
export default withStyles(styles)(connect(mapStateToProps, { fetchCurrentUserRequest, fetchCompanyRequest, uploadMediaCv })(Etape3));