import { useEffect } from 'react';
import { connect } from 'react-redux';
import { Redirect, useLocation } from 'react-router-dom';
import PropTypes from 'prop-types';
import { Container } from 'react-bootstrap';
import ErrorBoundary from './error-boundary';
import Header from './header';
import Footer from './footer';
import Loader from '../../shared/loader';
import ScrollToTop from '../../shared/scroll-to-top';
import { ANONYMOUS, AUTHENTICATED, INIT, LOADING } from '../../../redux/constants';
import './index.scss';

function MainLayout(props) {
  const { title, description, loginRequired } = props;

  const location = useLocation();

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

  useEffect(() => {
    if (title) document.title = title;
    if (description) document.description = description;
  }, [title, description]);

  if (loginRequired && props.authStatus === ANONYMOUS)
    return <Redirect to={`/login?next=${currentURL}`} />;

  return (
    <ErrorBoundary>
      <div className='rtl page-container'>
        <Header />
        <main>
          <Container>{renderContent(props)}</Container>
        </main>
        <Footer />
      </div>
      <ScrollToTop />
    </ErrorBoundary>
  );
}

function renderContent(props) {
  const { authStatus, loginRequired } = props;

  if (loginRequired && [INIT, LOADING].includes(authStatus)) {
    return (
      <div>
        <Loader />
      </div>
    );
  }
  if (!loginRequired || authStatus === AUTHENTICATED) return props.children;
}

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

MainLayout.defaultProps = {
  loginRequired: true
};

function mapStateToProps(state) {
  return {
    authStatus: state.auth.status
  };
}

export default connect(mapStateToProps)(MainLayout);
