import React, {Fragment} from 'react'
import { connect } from "react-redux";
import getConfig from 'next/config'
import PropTypes from 'prop-types';
import Stepper from '@material-ui/core/Stepper';
import Step from '@material-ui/core/Step';
import StepLabel from '@material-ui/core/StepLabel';
import { fetchJobRequest } from '../actions/ads'
import { fetchCompanyRequest } from '../actions/companies'
import { fetchCurrentUserRequest } from '../actions/user'
import { uploadMedia } from '../actions/media'
import LoaderVideo from './../components/templates/loaderVideo'
import Answer from '../components/organisms/Answer'
import LayoutBack from '../components/templates/LayoutBack'
import { withStyles } from '@material-ui/core/styles'
import Head from 'next/head'
import { Button, Typography } from '@material-ui/core';
import _ from 'lodash'
import Avatar from '@material-ui/core/Avatar';
import Snack from '../components/atoms/snack';
import KeyboardArrowRightIcon from '@material-ui/icons/KeyboardArrowRight';
import KeyboardArrowDownIcon from '@material-ui/icons/KeyboardArrowDown';
import Router from 'next/router'
import { errorMessageSelector } from '../reducers/media'
import dynamic from 'next/dynamic'

// import Recorder from '../components/organisms/Recorder'

const styles = theme => ({
  root: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'flex-start',
    margin: theme.spacing(1),
  },
  rootStepperContainer: {
    padding: theme.spacing(2, 12),
    width: '25vw',
    [theme.breakpoints.up('md')]: {
      width: '7vw',
      alignItems: 'center',
    },
    '& .MuiStep-horizontal, & .MuiStepLabel-iconContainer': {
      padding: '0 !important',
      [theme.breakpoints.up('md')]: {
        padding: 'inherit',
      },
    },
    '& .Mui-disabled .MuiStepConnector-line': {
      borderColor: theme.palette.answer.main + '!important',
    },
    '& .Mui-disabled .MuiStepIcon-root': {
      color: theme.palette.answer.main + '!important',
    },
  },
  rootStepperDefault: {
    '& .MuiStepConnector-line': {
      borderColor: theme.palette.secondary.dark,
    }
  },
  rootStepperActive: {
    '& .MuiStepConnector-line': {
      borderColor: theme.palette.primary.main,
    }
  },
  headerContainer: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'flex-start',
    padding: theme.spacing(2),
  },
  infoContainer: {
    display: 'flex',
    flexDirection: 'column',
    padding: theme.spacing(0, 1.5),
  },
  logoContainer: {
    display: 'flex',
    alignItems: 'center',
    width: 60,
    height: 60,
    backgroundColor: 'white',
    boxShadow: '0px 6px 15px rgba(30, 35, 39, 0.10)',
    border: 'solid 5px white',
    borderRadius: '6px',
  },
  recorderContainer: {
    //display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: '100%',
  },
  helpContainer: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: '400px',
  },
  logo: {
    width: 'inherit',
    height: '100%',
    objectFit: 'contain',
    borderRadius: '3px',
  },
  MuiAvatarImg: {
    objectFit: 'contain',
  },
  title: {
    fontSize: '1em',
    fontWeight: '500',
  },
  companyName: {
    fontSize: '0.9em',
    fontWeight: '300',
  },
  textContainer: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    '& p': {
      fontWeight: '300',
    },
    '& > p:nth-child(1)': {
      '& span': {
        fontWeight: '500',
      }
    },
    '& > p:nth-child(2)': {
      paddingBottom: theme.spacing(2),
      borderBottom: '1px solid #E8E8E8',
      '& span': {
        fontWeight: '500',
        color: theme.palette.primary.main,
      }
    },
  },
  rootButton: {
    textTransform: 'inherit',
  },
  underlined: {
    textDecoration: 'underline',
  },
  textButton: {
    fontWeight: '700',
    fontSize: '1.15em',
    paddingLeft: theme.spacing(2),
  },
  iconHelpButton: {
    fontSize: '1.5em',
    fontWeight: '500',
    padding: theme.spacing(0, 2),
    color: theme.palette.secondary.important,
  },
  helpButton: {
    color: theme.palette.primary.dark,
    backgroundColor: 'transparent',
    padding: theme.spacing(0, 2),
    margin: theme.spacing(1),
    width: '100%',
    '& span.MuiButton-label': {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
    }
  },

  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),
    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,
    },
  },
  HelpKeyboardArrowRightIcon: {
    fontSize: '2.5em',
    color: theme.palette.primary.dark,
  },
  InputKeyboardArrowRightIcon: {
    fontSize: '2.5em',
    color: theme.palette.secondary.main,
  },
  InputKeyboardArrowDownIcon: {
    fontSize: '2.5em',
    color: theme.palette.primary.main,
  },
});

const steps = ["", ""]

const Recorder = dynamic(() => import('../components/organisms/Recorder'), {
  ssr: false
})

const { publicRuntimeConfig } = getConfig()
class Reponse extends React.Component {
  state = {
    loading: true,
    activeStep: 0,
    data:{},
    openSnack: false,
    errors: {},
  };

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

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

  UNSAFE_componentWillReceiveProps(nextProps) {
    
    this.setState({
        loading: nextProps.loading,
        openSnack: !!!_.isEmpty(nextProps.errors),
        errors: !!!nextProps.errors ? { errors: { message: "" } } : nextProps.errors,
    })

    if(nextProps.media.status === 'success'){
      this.setActiveStep(1);
    }
  }

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

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

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

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

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

    this.props.uploadMedia(data)
  }

  handleClose = (event, reason) => {
      this.setState({ openSnack: false });
  }

  render() {
    const { loading, activeStep } = this.state;
    const { classes, menu, offre, company } = this.props;
    const logoUrl = (offre.company ? publicRuntimeConfig.symphonyUrl + publicRuntimeConfig.cachedMediaUrl + offre.company.logo : '');
    const logoCompanyUrl = ((company && company.logo) ? publicRuntimeConfig.symphonyUrl + publicRuntimeConfig.cachedMediaUrl + company.logo : '');

    let rootStepper = activeStep === 0 ? (
      classes.rootStepperDefault
    ) : (
        classes.rootStepperActive
      )
    return (
      <LayoutBack text="Candidature">
        <Head>
          <title>Candidature vidéo</title>
          <meta name="description" content="Talent's tube, postulez en video." />
          <meta key="robots" name="robots" content="noindex, nofollow"></meta>
          
        </Head>
        {/* https://codesandbox.io/s/ii0us */}
       { loading ? 
        <LoaderVideo /> :
       <Fragment>
        
        <section className={classes.headerContainer}>
         { !!offre.company && (
         
         <Fragment>
           <div className={classes.logoContainer}>
            <Avatar className={classes.logo} classes={{ img: classes.MuiAvatarImg }} src={logoUrl}  alt="companylogo"/>
          </div>
          <div className={classes.infoContainer}>
            <Typography gutterBottom variant="h5" component="h1" className={classes.title}>
              {!!offre.title? offre.title: ''}
            </Typography>
            <Typography gutterBottom variant="subtitle1" className={classes.companyName}>
              {!!offre.company.brand_name? offre.company.brand_name: ''}
            </Typography>
            {/* ville */}
          </div>
          </Fragment>)
          }
          { !!company.brand_name && (<Fragment><div className={classes.logoContainer}>
            <Avatar className={classes.logo} classes={{ img: classes.MuiAvatarImg }} src={logoCompanyUrl} alt="companylogo"/>
          </div>
          <div className={classes.infoContainer}>
            <Typography gutterBottom variant="h5" component="h1" className={classes.title}>
              {!!company.brand_name? company.brand_name: ''}
            </Typography>
            {/* <Typography gutterBottom variant="subtitle1" className={classes.companyName}>
              {!!offre.company.brand_name? offre.company.brand_name: ''}
            </Typography> */}
            {/* ville */}
          </div></Fragment>)
          }

        </section>

        <Stepper activeStep={activeStep} classes={{ root: rootStepper }} className={classes.rootStepperContainer}>
          {steps.map((label, index) => {
            return (
              <Step key={label} >
                <StepLabel>{label}</StepLabel>
              </Step>
            );
          })}
        </Stepper>
        {loading ? ( <Loader />)
        : activeStep === 0 ? 
        (
          <div className={classes.root}>

            <div className={classes.textContainer}>
              <Typography gutterBottom align="center">
              Vous allez postuler en <span>vidéo</span> !
              </Typography>
              <Typography gutterBottom align="center">
                C'est <span>simple</span>,<span> rapide</span> et <span>plus humain</span>
              </Typography>    
            </div>

            <div className={ classes.helpContainer}>
              <Button component="span" className={classes.helpButton} classes={{ root: classes.rootButton }} onClick={() => Router.push(`/Conseils`)}> 
              <Typography align="center" className={classes.textButton}>
                Par <span className={classes.underlined}>ici</span> pour quelques conseils !               
              </Typography>
              <KeyboardArrowRightIcon className={ classes.HelpKeyboardArrowRightIcon }/>
              </Button>
              </div>
    { /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 réponse
                </Typography>
                <KeyboardArrowRightIcon className={ classes.InputKeyboardArrowRightIcon }/>
                </Button>
              </label>
            </Fragment>
            ):
            (
              <div className={classes.recorderContainer}>
                <Recorder uploader={this.props.uploadMedia} />
              </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='/static/images/import.svg' className={classes.iconButton} />
                <Typography align="left" className={classes.textButton}>
                  J'<span className={classes.underlined}>importe</span> ma vidéo de réponse
                  
              </Typography>
              <KeyboardArrowDownIcon className={ classes. InputKeyboardArrowDownIcon }/>
              </Button>
            </label>
            
          </div>
        ) :
          (
            <Answer mediaId={!!this.props.media && this.props.media.id}
             companyId={!!offre.company ? offre.company.id : !!company.brand_name ? company.id : null}
             adId={offre.id}
             >
             </Answer>
          )}
           <Snack variant="error" message={!!!_.isEmpty(this.state.errors) && this.state.errors.message }
                    openSnack={this.state.openSnack} onClose={this.handleClose} />
          </Fragment>
        }
          </LayoutBack>
    )

  }

}

Reponse.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) {
  
  return {
    loading: !!state.answer.loading || !!state.media.loading,
    media: state.media,
    offre: state.ad,
    errors: state.answer.errors || errorMessageSelector(state),
    user: state.user,
    company: state.company
  };
}

Reponse.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(connect(mapStateToProps, { fetchCurrentUserRequest, fetchJobRequest, fetchCompanyRequest, uploadMedia })(Reponse));