import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import { always } from 'ramda';
import Grid from '@material-ui/core/Grid';
import { withStyles } from '@material-ui/core/styles';

import Refresher from '../../containers/Refresher/Refresher.state';
import ScrollToTop from '../ScrollToTop/ScrollToTop';
import Auth from '../Auth/Auth';
import { sessionStorage } from '../../utils/globals';

const styles = theme => ({
  layout: {
    height: '100vh'
  },
  main: {
    flexGrow: 1,
    minHeight: 'max-content',
    overflowY: 'scroll',
    padding: theme.spacing.unit * 3,
  }
});

/* eslint-disable no-undef */
const Layout = ({
  header,
  main,
  footer,
  classes,
  resource,
  isAuthorised,
  resetPermissions,
  authorise,
  location,
  ioRequest: { status },
}) => (
  <Auth
    isAuthorised={isAuthorised}
    resetPermissions={resetPermissions}
    authorise={authorise}
    location={location}
    resource={resource}
    loggedin={!!(sessionStorage && sessionStorage.getItem && sessionStorage.getItem('token'))}
    loginPath="/login"
    unauthorisedPath="/unauthorized"
    ioRequestStatus={status}
  >
    <Fragment>
      <Refresher />
      <ScrollToTop />
      <Grid
        className={classes.layout}
        container
        direction="column"
        wrap="nowrap"
      >
        {header}
        <Grid
          className={classes.layout}
          container
          direction="column"
          wrap="nowrap"
        >
          {header}
          <Grid
            container
            item
            justify="center"
            xs={12}
            className={classes.main}
          >
            {main}
          </Grid>
          {footer}
        </Grid>
      </Grid>
    </Fragment>
  </Auth>
);
/* eslint-disable no-undef */

Layout.propTypes = {
  header: PropTypes.node,
  main: PropTypes.node,
  footer: PropTypes.node,
  isAuthorised: PropTypes.bool,
  authorise: PropTypes.func,
  resetPermissions: PropTypes.func,
  location: PropTypes.shape({
    pathname: PropTypes.string,
  }),
  ioRequest: PropTypes.shape({
    status: PropTypes.string,
  }),
  resource: PropTypes.string,
};

Layout.defaultProps = {
  header: null,
  footer: null,
  main: null,
  isAuthorised: false,
  authorise: always(),
  resetPermissions: always(),
  location: {},
  resource: '',
  ioRequest: {
    status: '',
  },
};

export default withStyles(styles)(Layout);
