import React, {Fragment} from 'react'
import {connect} from "react-redux";
import {makeStyles} from '@material-ui/styles';
import KeyboardArrowRightIcon from '@material-ui/icons/KeyboardArrowRight';
import KeyboardArrowDownIcon from '@material-ui/icons/KeyboardArrowDown';
import {Button, Typography} from '@material-ui/core';
import dynamic from 'next/dynamic'
import {withStyles} from '@material-ui/core/styles'
import {uploadMediaPres} from '../../actions/media'
import {errorMessageSelector} from '../../reducers/media'
import {fetchCompanyRequest} from '../../actions/companies'
import {fetchCurrentUserRequest} from '../../actions/user'
import VideoVimeo from '../atoms/VideoVimeo'
import Router from 'next/router'
import LoaderVideo from '../templates/loaderVideo'
import Ar from "lodash/array"
import Snackbar from '@material-ui/core/Snackbar';
import { Alert, AlertTitle } from '@material-ui/lab';
import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 } from 'react-html-parser';
import Grid from '@material-ui/core/Grid';
import Container from '@material-ui/core/Container';
import Hidden from '@material-ui/core/Hidden';

const styles = theme => ({
    container: {
        width: '100%',
    },
    root: {
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'flex-start',
        margin: theme.spacing(1),
        flexWrap: 'wrap',
        overflow: 'hidden',
        backgroundColor: theme.palette.background.paper,
    },
    
    recorderContainer: {
        //display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        width: '100%'
    },
    rootButton: {
        textTransform: 'inherit'
    },
    underlined: {
        textDecoration: 'underline'
    },
    textButton: {
        fontWeight: '700',
        fontSize: '1.15em',
        paddingLeft: theme.spacing(2)
    },
    videoPresentation: {    
        width: "100%",
        height: "100%"
    },
    conseilButton: {
        color: "#ffffff",
        backgroundColor:  "#25D89A",
        padding: theme.spacing(3, 2),
        margin: theme.spacing(1),
        width: "100%",
        textAlign: "right",
        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: "#ffffff",
            backgroundColor:  "#25D89A",
        }
    },
    captureButton: {
        color: theme.palette.secondary.main,
        backgroundColor: theme.palette.primary.main,
        padding: theme.spacing(5, 2),
        margin: theme.spacing(1),
        boxShadow: '0 6px 10px 0 rgba(0, 0, 0, 0.14), 0 1px 4px 0 rgba(0, 0, 0, 0.12), 0 3px 5px -1px rgba(0, 0, 0, 0.14)',
        '&:hover': {
          backgroundColor: 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: "100%",
        textAlign: "right",
        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,
        }
    },
    InputKeyboardArrowDownIconBlank: {
        fontSize: '2.5em',
        color: "#ffffff",
        textAlign: "right"
    },
    InputKeyboardArrowDownIcon: {
        fontSize: '2.5em',
        color: "#1689FB",
        textAlign: "right"
    },
    buttons :{
        display: "inline-table",
    }
});
const Recorder = dynamic(() => import ('../organisms/Recorder'), {ssr: false})
class Etape2 extends React.Component {
    state = {
        loading: true,
        activeStep: 0,
        data: {},
        openSnack: false,
        errors: {},
        success : {}
    };
    

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

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

    UNSAFE_componentWillReceiveProps(nextProps) {

        this.setState({
            loading: nextProps.loading,
            openSnack: !!!_.isEmpty(nextProps.errors),
            errors: !!!nextProps.errors
                ? {
                    errors: {
                        message: ""
                    }
                }
                : nextProps.errors,
            videoPres: nextProps.videoPres,
            video: nextProps.video
        })
        //window.location.reload(false);
        if (nextProps.media.status === 'success') {
            const success = {};
            success.message ="Vidéo mise à jour";
            this.setState({ success });
            this.setActiveStep(1);
        }
    }

    setActiveStep = (step) => {
        this.setState({activeStep: step})
    }

    inputFilesystemChange = (e) => {
        this.uploadMediaPres(e)
    }

    inputCamRecorderChange = (e) => {
        this.uploadMediaPres(e)
    }

    uploadMediaPres = (e) => {
        var file = e.target.files[0]

        const data = new FormData()
        data.append('upload', file)
        //this.setState({ videoPres: videoPres })
        
        this
            .props
            .uploadMediaPres(data)
    }

    AfficherSuccess() {
      if (!this.state.success || !this.state.success.message) { 
          
      } 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 "";
    }

    handleClose = (event, reason) => {
        this.setState({openSnack: false});
    }
   
    render() {
        const {classes, company} = this.props;
        const {loading, activeStep} = this.state;
        let video;
        if (this.state.videoPres) {
            video = <VideoVimeo videoId={Ar.last(_.split(this.state.videoPres, '/'))}  autoplay='1' classesOverride="videoPresentation"/>;
        } else {
            video = "";
        }
        return (
            <section className={classes.container}>
                <Fragment>
                    {this.AfficherSuccess()}
                    { loading ? <LoaderVideo textePrincipal="Votre vidéo est en cours d’envoi..." texteSecondaire="Veuillez rester sur la page pendant le chargement qui peut durer plusieurs minutes."/>  : <div></div> }
                    
                    <div className={classes.root}>
                    <Hidden xsUp>
                            &nbsp;                   
                        </Hidden>
                    <Container maxWidth="md">
                        
                        <Grid container
                            justify="center"
                            alignItems="center" 
                            spacing={2}
                            className={classes.buttons}>
                            <Grid item xs={12} sm={12} md={12} lg={6} lg={6}>
                                


                            { /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)  ?
                                (
                                    <Fragment >
                                    <input
                                        type="file" accept="video/*" capture="camcorder"
                                        className={classes.input}
                                        style={{ display: 'none' }}
                                        id="record-button-file"
                                        multiple
                                        onChange={this.inputCamRecorderChange}
                                    />
                                    <label htmlFor="record-button-file">
                                        <Button component="span" className={classes.captureButton} classes={{ root: classes.rootButton }}>
                                        <img alt="talents-tube" src='/static/images/capture.svg' className={classes.iconButton} />
                                        <Typography align="left" className={classes.textButton}>
                                            Je <span className={classes.underlined}>réalise</span> ma vidéo de présentation
                                        </Typography>
                                        <KeyboardArrowRightIcon className={ classes.InputKeyboardArrowRightIcon }/>
                                        </Button>
                                    </label>
                                    </Fragment>
                                ):
                                (

                                
                                <div className={classes.recorderContainer}>
                                    <Recorder uploader={this.props.uploadMediaPres} titreBouton="Remplacer ma vidéo"/>
                                    
                                </div>
                                )
                            }
                            </Grid>
                            <Grid item xs={12} sm={12} md={12} lg={6} xl={6}>
                                <div> 
                                    <label htmlFor="import-conseil">
                                        <Button
                                            component="span"
                                            className={classes.conseilButton}
                                            classes={{
                                            root: classes.rootButton}}
                                            onClick={() => Router.push(`/Conseils`)}>
                                            <img
                                                alt="talents-tube"
                                                src='/statique/images/conseils-talentstube.svg'
                                                className={classes.iconButton}/>
                                            <Typography align="left" className={classes.textButton}>
                                                <span className={classes.underlined}>Comment</span> créer ma vidéo 
                                            </Typography>
                                            <KeyboardArrowDownIcon className={classes.InputKeyboardArrowDownIconBlank}/>
                                        </Button>
                                    </label>
                                </div>
                                <div>
                                        <input
                                            type="file"
                                            accept="video/*"
                                            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.svg'
                                                    className={classes.iconButton}/>
                                                <Typography align="left" className={classes.textButton}>
                                                    J'<span className={classes.underlined}>importe</span> ma vidéo de présentation

                                                </Typography>
                                                <KeyboardArrowDownIcon className={classes.InputKeyboardArrowDownIcon}/>
                                            </Button>
                                        </label>
                                    </div>
                            
                            </Grid> 
                            <Hidden xsUp>
                                &nbsp;                   
                            </Hidden>
                        
                            <Grid item xs={12} sm={12} md={12} lg={12} xl={12}>
                                <div className={classes.videoPresentation}>
                                    {video}   
                                </div>                
                            </Grid>
                            
                        </Grid>
                    </Container>      
                    </div>
                    {/* <div className={classes.textContainer}>
                        
                    </div> */}
                            
                </Fragment>
            </section>

        );
    }

}

Etape2.getInitialProps = function (context) {

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

    if (!!companyId) 
        context.store.dispatch(fetchCompanyRequest(companyId))

    return {}; //leave this please
}

function mapStateToProps(state) {

    return {
        loading: !!state.media.loading,
        media: state.media,
        offre: state.ad,
        //errors:  errorMessageSelector(state),
        user: state.user,
        company: state.company
    };
}

export default withStyles(styles)(connect(mapStateToProps, {fetchCurrentUserRequest, fetchCompanyRequest, uploadMediaPres})(Etape2));