import {Component, Fragment} from 'react';
import {withRouter, Redirect} from 'react-router-dom';
import PropTypes from 'prop-types';
import {UseUser} from '../../shared/use-user';
import Header from './header';
import Container from '../../shared/container';
import Footer from './footer';
import ScrollToTop from '../../shared/buttons/scroll-to-top';
import Loader from '../../shared/loader';

class MainLayout extends Component {
  componentDidMount() {
    const {title, description} = this.props;
    if (title) document.title = title;
    if (description) document.description = description;
  }

  renderContent = status => {
    const {loginRequired} = this.props;

    if (loginRequired && status === 'loading') return <div><Loader/></div>;
    if (!loginRequired || status === 'success') return this.props.children;
  };

  render() {
    const {location, loginRequired} = this.props;
    const currentURL = `${location.pathname}${location.search.replace('&', ';')}`;

    return (
      <UseUser>
        {({status}) => {
          if (loginRequired && status === 'error') return <Redirect to={`/login?next=${currentURL}`}/>;

          return (
            <Fragment>
              <div className='flex flex-col h-screen'>
                <Header/>
                <main className='flex-1 py-4'>
                  <Container>
                    {this.renderContent(status)}
                  </Container>
                </main>
                <Footer/>
              </div>
              <ScrollToTop/>
            </Fragment>
          );
        }}
      </UseUser>
    );
  }
}

MainLayout.propTypes = {
  title: PropTypes.string,
  description: PropTypes.string,
  loginRequired: PropTypes.bool.isRequired,
  location: PropTypes.object.isRequired,
  children: PropTypes.oneOfType([
    PropTypes.node,
    PropTypes.arrayOf(PropTypes.node)
  ])
};

MainLayout.defaultProps = {
  loginRequired: true
};

export default withRouter(MainLayout);
