import React, { Fragment, Children } from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import { withStyles, getMuiTheme } from '@material-ui/core/styles';
import MenuIcon from '@material-ui/icons/Menu';
import Link from 'next/link'
import Drawer from '@material-ui/core/Drawer';
import Divider from '@material-ui/core/Divider';
import HomeIcon from '@material-ui/icons/HomeOutlined';
import OfferIcon from '@material-ui/icons/LocalOfferOutlined';
import CompanyIcon from '@material-ui/icons/DomainOutlined';
import HelpIcon from '@material-ui/icons/HelpOutline';
import VideoIcon from '@material-ui/icons/OndemandVideoOutlined';
import NotesIcon from '@material-ui/icons/NotesOutlined';
import SupervisorAccountIcon from '@material-ui/icons/SupervisorAccount';
import PersonIcon from '@material-ui/icons/Person';
import PersonAddIcon from '@material-ui/icons/PersonAdd';
import WorkOutlineIcon from '@material-ui/icons/WorkOutline';
import AccountCircleOutlinedIcon from '@material-ui/icons/AccountCircleOutlined';
import FolderSharedIcon from '@material-ui/icons/FolderShared';
import AccountCircleIcon from '@material-ui/icons/AccountCircle';
import PermContactCalendar from '@material-ui/icons/PermContactCalendar';
import VideoCam from '@material-ui/icons/Videocam';
import SettingsIcon from '@material-ui/icons/Settings';
import PowerSettingsNewIcon from '@material-ui/icons/PowerSettingsNew';
import ArrowForward from '@material-ui/icons/ArrowForward';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import { ListItemText } from '@material-ui/core';
import Loader from './../templates/loader'
import { connect } from 'react-redux'
import { fetchCurrentUserRequest } from "../../actions/user";
import { requestLogout } from "../../actions/auth";
import Button from '@material-ui/core/Button';
import withWidth, { isWidthUp } from '@material-ui/core/withWidth'
import Typography from '@material-ui/core/Typography';
import { withRouter } from "next/router";
import ActiveLink from "./../atoms/Activelink";
import axios from 'axios';
import setAuthorizationHeader from "../../data/setAuthorizationHeader";
import getConfig from 'next/config'

const styles = theme => ({
  root: {
    width: '100%',
    position: 'relative',
    zIndex: '999',
    '& a': {
      textDecoration: 'none'
    }
  },
  toolbar: {
    height: '64px',
  },
  grow: {
    flexGrow: 1,
  },
  menuButton: {
    marginLeft: -12,
    marginRight: 20,
    display: 'block'
  },
  menuLogo: {
    cursor: 'pointer',
    [theme.breakpoints.down('md')]: {
      width: '200px'
    },
    [theme.breakpoints.down('sm')]: {
      width: '130px'
    },
  },
  menuAvatar: {
    width: '2.5em',
    borderRadius: '50%',
    marginTop: theme.spacing(2),
    marginLeft: theme.spacing(2),
  },
  menuUserName: {
    color: theme.palette.menu.emailText,
    fontSize: '1.3rem',
    fontWeight: '500',
  },
  menuUserEmail: {
    color: theme.palette.menu.emailText,
    fontSize: '0.9rem',
    fontWeight: '200',
  },
  darkDivider: {
    background: 'whitesmoke',
    opacity: '0.1',
  },
  List: {
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'space-between',
    height: '100%',
    paddingTop: 0,
    paddingBottom: 0,
    '&>a:first-child': {
      minHeight: '64px',
      height: '64px',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
    },
    [theme.breakpoints.up('md')]: {
      '&>a:first-child': {
        height: '64px',
      },
      '&>a:first-child li': {
        height: '64px',
        alignItems: 'center',
      },
    },
  },
  fullList: {
    width: 'auto',
    cursor: 'pointer',
    paddingBottom: 0
  },
  lightFullList: {
    height: '100vh',
    backgroundColor: theme.palette.background.default,
  },
  darkFullList: {
    backgroundColor: theme.palette.background.dark,
  },
  lightMenuItem: {
    color: theme.palette.menu.lightText,
    textDecoration: 'none',
  },
  darkMenuItem: {
    color: theme.palette.menu.darkText,
    textDecoration: 'none',
  },
  darkMenuItemSpecific: {
    '&:hover,&:active': {
      color: theme.palette.primary.main,
    }
  },
  links: {
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'space-between',
    height: '100%',
  },
  linkGroup: {
    padding: theme.spacing(1.2, 0),
    paddingLeft: 0,
  },
  videothequeLinkGroup: {
    backgroundColor: theme.palette.background.videotheque,
  },
  blogLinkGroup: {
    backgroundColor: theme.palette.background.blog,
  },
  recruteurLinkGroup: {
    backgroundColor: theme.palette.background.recruteur,
  },
  rootListItem: {
    padding: theme.spacing(1, 2),
    cursor: 'pointer',
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'flex-start',
  },
  rootListItemIcon: {
    padding: theme.spacing(1, 2),
    cursor: 'pointer',
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
  },
  ListItemUserConnected: {
    flexDirection: 'column',
  },
  ListItemText: {
    fontSize: '1em',
  },
  icon: {
    paddingRight: theme.spacing(2.5),
  },
  iconAccount: {
    color: theme.palette.primary.dark,
  },
  title: {
    color: theme.palette.secondary.main,
    fontSize: '1.5em'
  },
  email: {
    color: theme.palette.menu.emailText,
    fontSize: '0.9em'
  },
  button: {
    padding: theme.spacing(0.5, 1),
    textTransform: 'inherit',
    '& svg': {
      width: '0.7em',
      height: '0.7em',
    },
  },

  active: {
    '& span, & svg': {
      color: theme.palette.primary.main + ' !important',
    },
  },

  //DESKTOP PART

  desktopMenuItem: {
    [theme.breakpoints.down('md')]: {
      padding: theme.spacing(0.4),
    },
    '& span.MuiTypography-root': {
      fontSize: '0.8rem',
      fontWeight: '500',
    },
  },
  desktopMenuList: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 0,
  },
  appBarDesktopSection: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  appBarDesktopSection1: {
    padding: theme.spacing(0, 2),
    height: '100%',
    borderRight: 'solid 1px whitesmoke',
  },
  appBarDesktopSection2: {
    width: '100%',
    justifyContent: 'space-between',
    padding: theme.spacing(0, 2),
    '& ul': {
      width: '95%',
    },
    '& ul>div': {
      display: 'flex',
    },
    '& ul > div:nth-child(1) a span': {
      color: theme.palette.primary.dark,
      '&:hover, &:active': {
        color: theme.palette.primary.main,
      }
    },
    '& .MuiListItemText-root': {
      padding: theme.spacing(0, 1),
      [theme.breakpoints.down('md')]: {
        padding: theme.spacing(0),
      },
    },
    '& a:last-child .MuiButtonBase-root span': {
      color: theme.palette.secondary.main,
    },
  },
  appBarDesktopSection3: {
    padding: theme.spacing(0, 2),
    height: '100%',
    backgroundColor: theme.palette.primary.dark,
    '& a': {
      display: 'flex',
      alignItems: 'flex-end',
    },
    '& span, & svg': {
      color: theme.palette.secondary.main,
    },
  },
  toolbarDesktop: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    height: '64px',
  },
  desktopMenuButtonLogin: {
    background: theme.palette.primary.main,
    borderColor: theme.palette.primary.main,
  },
  rootListItemDesktop: {
    [theme.breakpoints.up('md')]: {
      padding: theme.spacing(1),
    },
  },
  iconDesktop: {
    paddingRight: theme.spacing(2.5),
    [theme.breakpoints.up('md')]: {
      paddingRight: 0,
    },
  },
});
let urlEnv;

class Header extends React.Component {
  state = {
    top: false,
    left: false,
    bottom: false,
    right: false,
    toggle: true
  };



  componentDidMount() {

  }

  

  toggleDrawer = (side, open) => () => {
    this.setState({
      [side]: open,
    });
  };

  onRedirectAccount = e => {
      urlEnv = (process.env.NODE_ENV !== 'production') ? '//localhost/app_dev.php' : process.env.SERVER_URL;
      e.preventDefault();
      var redirectAccountUrl = urlEnv + "/api/talent?bearer=" + localStorage.getItem("ttJWT");
      window.open(redirectAccountUrl);
  }

  toggle = () => this.setState(state => ({ toggle: !state.toggle }))

  render() {
    const { classes } = this.props;
    const { publicRuntimeConfig } = getConfig();


    return (
      <div className={classes.root}>
        <Drawer anchor="left" open={this.state.left} onClose={this.toggleDrawer('left', false)}>
          <div
            tabIndex={0}
            role="button"
            onClick={this.toggleDrawer('left', false)}
            onKeyDown={this.toggleDrawer('left', false)}
          >
            <div className={classes.fullList + ' ' + classes.lightFullList}>
              <List className={classes.List}>

                <Link href="/"  >
                  <a className={classes.darkMenuItem}><ListItem classes={{ root: classes.rootListItem }}>
                    <img alt="talents-tube" src='/statique/images/logos/TalentsTube_logo-color.svg' className={classes.menuLogo} />
                  </ListItem></a>
                </Link>


                <Divider />
                <div className={classes.links}>
                  <div className={classes.linkGroup}>
                    <ActiveLink activeClassName={classes.active} href="/"  >
                      <a className={classes.darkMenuItem}><ListItem classes={{ root: classes.rootListItemIcon }}>
                        <HomeIcon className={classes.icon} />
                        <ListItemText classes={{ primary: classes.ListItemText }} primary='Accueil'>
                        </ListItemText>
                      </ListItem></a>
                    </ActiveLink>
                    <ActiveLink activeClassName={classes.active} href="/Offres"  >
                      <a className={classes.darkMenuItem + ' ' + classes.darkMenuItemSpecific}><ListItem classes={{ root: classes.rootListItemIcon }}>
                        <OfferIcon className={classes.icon} />
                        <ListItemText classes={{ primary: classes.ListItemText }} primary={`Offres d'emploi`}>
                        </ListItemText>
                      </ListItem></a>
                    </ActiveLink>
                    <ActiveLink activeClassName={classes.active} href="/Entreprises"  >
                      <a className={classes.darkMenuItem + ' ' + classes.darkMenuItemSpecific}><ListItem classes={{ root: classes.rootListItemIcon }}>
                        <CompanyIcon className={classes.icon} />
                        <ListItemText classes={{ primary: classes.ListItemText }} primary='Nos entreprises'>
                        </ListItemText>
                      </ListItem></a>
                    </ActiveLink>
                    <ActiveLink activeClassName={classes.active} href="/Help"  >
                      <a className={classes.darkMenuItem + ' ' + classes.darkMenuItemSpecific}><ListItem classes={{ root: classes.rootListItem }}>
                        <HelpIcon className={classes.icon} />
                        <ListItemText classes={{ primary: classes.ListItemText }} primary='Comment ça marche ?'>
                        </ListItemText>
                      </ListItem></a>
                    </ActiveLink>
                  </div>
                  <div>
                    <div className={classes.blogLinkGroup}>
                      <a href={publicRuntimeConfig.blogUrl} className={classes.lightMenuItem}><ListItem classes={{ root: classes.rootListItemIcon }}>
                        <NotesIcon className={classes.icon} />
                        <ListItemText classes={{ primary: classes.ListItemText }} primary='Blog'>
                        </ListItemText>
                      </ListItem>
                      </a>
                    </div>
                    <div className={classes.recruteurLinkGroup}>
                      <a href={publicRuntimeConfig.symphonyUrl } className={classes.lightMenuItem}><ListItem classes={{ root: classes.rootListItemIcon }}>
                        <SupervisorAccountIcon className={classes.icon} />
                        <ListItemText classes={{ primary: classes.ListItemText }} primary='Recruteurs'>
                        </ListItemText>
                      </ListItem></a>
                    </div>
                  </div>

                </div>
              </List>

            </div>
          </div>
        </Drawer>

        <Drawer anchor="right" open={this.state.right} onClose={this.toggleDrawer('right', false)}>
          <div
            tabIndex={0}
            role="button"
            onClick={this.toggleDrawer('right', false)}
            onKeyDown={this.toggleDrawer('right', false)}
          >{!!this.props.loading &&
            (<Loader />
            )}
            {!!!this.props.loading && !!!this.props.fetched
              &&
              <div className={classes.fullList + ' ' + classes.darkFullList}>
                <List>
                  <Link href="/"  >
                    <a className={classes.darkMenuItem + ' cypFrontPage'}><ListItem classes={{ root: classes.rootListItemIcon }}>
                      <img alt="talents-tube" src='/statique/images/logos/TalentsTube_logo-blanc.svg' className={classes.menuLogo} />
                    </ListItem></a>
                  </Link>


                  <Divider light={true} />

                  <div className={classes.linkGroup}>
                    <Link href="/Login" >
                      <a className={classes.lightMenuItem + ' cypConnexion'}><ListItem classes={{ root: classes.rootListItemIcon }} >
                        <PersonIcon className={classes.icon} />
                        <ListItemText classes={{ primary: classes.ListItemText }} primary='Connexion'>
                        </ListItemText>
                      </ListItem></a>
                    </Link>
                    {/* TODO */}
                    <Link href="/Login?inscription=true"  >
                      <a className={classes.lightMenuItem + ' cypRegister'}><ListItem classes={{ primary: classes.ListItemText }} classes={{ root: classes.rootListItem }}>
                        <PersonAddIcon className={classes.icon} />
                        <ListItemText primary='Inscription'>
                        </ListItemText>
                      </ListItem></a>
                    </Link>
                  </div>

                  <Divider light={true} />

                  <div className={classes.linkGroup}>
                    <a href={publicRuntimeConfig.symphonyUrl + "/"} className={classes.lightMenuItem}><ListItem classes={{ primary: classes.ListItemText }} classes={{ root: classes.rootListItemIcon }}>
                      <WorkOutlineIcon className={classes.icon} />
                      <ListItemText primary='Connexion recruteurs'>
                      </ListItemText>
                    </ListItem>
                    </a>
                  </div>
                </List>
              </div>}
            {!!!this.props.loading && !!this.props.fetched &&
              <Fragment>
                {this.props.user.picture ?
                  <img alt="talents-tube" src={publicRuntimeConfig.symphonyUrl +publicRuntimeConfig.postedContentUrl+ this.props.user.picture} className={classes.menuAvatar} />
                  :
                  <img alt="talents-tube" src='/static/images/default/account-avatar-default.svg' className={classes.menuAvatar} />
                }
                <ListItem classes={{ root: classes.rootListItem }} className={classes.ListItemUserConnected}>
                  <Typography gutterBottom component="h1" className={classes.menuUserName}>
                    {this.props.user.firstname + " " + this.props.user.lastname}
                  </Typography>

                  <Typography gutterBottom component="h3" className={classes.menuUserEmail} >
                    {this.props.user.email}
                  </Typography>
                </ListItem>

                <Divider className={classes.darkDivider} />

                {/* TODO:real links */}
                <Link href="/Candidatures"  >
                  <a className={classes.lightMenuItem}><ListItem classes={{ root: classes.rootListItemIcon }}>
                    <FolderSharedIcon className={classes.icon} />
                    <ListItemText primary='Mes candidatures'>
                    </ListItemText>
                  </ListItem></a>
                </Link>
                <Link href="/profileStep"  >
                <a className={classes.lightMenuItem}><ListItem classes={{ root: classes.rootListItemIcon }}>
                    <AccountCircleIcon className={classes.icon} />
                    <ListItemText primary='Mon compte'>
                    </ListItemText>
                  </ListItem></a>
                </Link>
                
                <Link href="/Parametres"  >
                  <a className={classes.lightMenuItem}><ListItem classes={{ root: classes.rootListItemIcon }}>
                    <SettingsIcon className={classes.icon} />
                    <ListItemText primary='Paramètres de notification'>
                    </ListItemText>
                  </ListItem></a>
                </Link>
                <Link href="/" >
                  <a onClick={() => {
                    localStorage.removeItem("ttJWT");
                    return this.props.requestLogout();
                  }} className={classes.lightMenuItem}><ListItem classes={{ root: classes.rootListItemIcon }}>
                      <PowerSettingsNewIcon className={classes.icon} />
                      <ListItemText primary='Déconnexion'>
                      </ListItemText>
                    </ListItem></a>
                </Link>
              </Fragment>
            }
          </div>
        </Drawer>

        {isWidthUp('md', this.props.width) ?
          (<AppBar position="static" className={classes.appBar}>
            <Toolbar disableGutters={true} className={classes.toolbarDesktop}>
              <section className={classes.appBarDesktopSection + ' ' + classes.appBarDesktopSection1}>
                <Link href="/"  >
                  <a className={classes.darkMenuItem}>
                    <ListItem classes={{ root: classes.rootListItemDesktop }}>
                      <img alt="talents-tube" src='/statique/images/logos/TalentsTube_logo-color.svg' className={classes.desktopMenuLogo} />
                    </ListItem>
                  </a>
                </Link>
              </section>
              <section className={classes.appBarDesktopSection + ' ' + classes.appBarDesktopSection2}>
                <IconButton className={classes.menuButton} onClick={this.toggleDrawer('left', true)}
                  color="inherit" aria-label="Open drawer">
                  <MenuIcon />
                </IconButton>

                <List className={classes.desktopMenuList}>
                  <div>
                    <ActiveLink activeClassName={classes.active} href="/Offres"  >
                      <a className={classes.desktopMenuItem}>
                        <ListItemText primary="Offres d'emploi">
                        </ListItemText>
                      </a>
                    </ActiveLink>
                    <ActiveLink activeClassName={classes.active} href="/Entreprises"  >
                      <a className={classes.desktopMenuItem}>
                        <ListItemText primary='Nos entreprises'>
                        </ListItemText>
                      </a>
                    </ActiveLink>
                    <ActiveLink activeClassName={classes.active} href="/Help"  >
                      <a className={classes.desktopMenuItem}>
                        <ListItemText primary='Comment ça marche ?'>
                        </ListItemText>
                      </a>
                    </ActiveLink>
                  </div>

                  <div>
                    {!!!this.props.loading && !!!this.props.fetched &&
                      <Fragment>
                        <Link href="/Login?inscription=true"  >
                          <a className={classes.desktopMenuItem}>
                            <ListItem classes={{ root: classes.rootListItemDesktop }}>
                              <Button
                                variant="outlined"
                                className={classes.button + ' ' + classes.desktopMenuButtonRegister}>
                                <PersonAddIcon className={classes.iconDesktop} />
                                <ListItemText classes={{ primary: classes.ListItemText }} primary='Inscription'></ListItemText>
                              </Button >
                            </ListItem>
                          </a>
                        </Link>

                        <Link href="/Login"  >
                          <a className={classes.desktopMenuItem}>
                            <ListItem classes={{ root: classes.rootListItemDesktop }}>
                              <Button
                                variant="outlined"
                                className={classes.button + ' ' + classes.desktopMenuButtonLogin}>
                                <PersonIcon className={classes.iconDesktop} />
                                <ListItemText classes={{ primary: classes.ListItemText }} primary='Connexion'></ListItemText>
                              </Button >
                            </ListItem>
                          </a>
                        </Link>
                      </Fragment>
                    }
                    {!!!this.props.loading && !!this.props.fetched &&
                      <IconButton
                        edge="end"
                        aria-label="Profile"
                        aria-controls={'primary-search-account-menu'}
                        aria-haspopup="true"
                        onClick={this.toggleDrawer('right', true)}
                        className={classes.iconAccount + ' cypConnexionMenu'}
                      >
                        <AccountCircleOutlinedIcon />
                      </IconButton>
                    }
                  </div>
                </List>
              </section>
              <section className={classes.appBarDesktopSection + ' ' + classes.appBarDesktopSection3}>

                <a href={publicRuntimeConfig.symphonyUrl + "/"} className={classes.desktopMenuItem}>
                  <ListItemText primary='Espace recruteurs'>
                  </ListItemText>
                  <ArrowForward className={classes.icon} />
                </a>
              </section>
            </Toolbar>
          </AppBar>)
          :
          (
            <AppBar position="static" className={classes.appBar}>
              <Toolbar className={classes.toolbar}>
                <IconButton className={classes.menuButton} onClick={this.toggleDrawer('left', true)}
                  color="inherit" role="button">
                  <MenuIcon />
                </IconButton>
                <div className={classes.grow} />
                <Link href="/"  >
                  <a><img alt="talents-tube" src='/statique/images/logos/TalentsTube_logo-color.svg' className={classes.menuLogo} /></a>
                </Link>
                <div className={classes.grow} />
                <IconButton
                  edge="end"
                  aria-label="Profile"
                  aria-controls={'primary-search-account-menu'}
                  aria-haspopup="true"
                  onClick={this.toggleDrawer('right', true)}
                  className={classes.iconAccount + ' cypConnexionMenu'}

                >
                  <AccountCircleOutlinedIcon />
                </IconButton>
              </Toolbar>
            </AppBar>
          )}
      </div >
    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.user,
    fetched: !!state.user.fetched,
    loading: !!state.user.loading
  };
}
export default (connect(mapStateToProps, { fetchCurrentUserRequest, requestLogout })(withStyles(styles)(withWidth()(Header))));