import { ReactNode, useEffect } from 'react';
import { Redirect, RouteComponentProps, withRouter } from 'react-router-dom';
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';
import { getLoginRedirectURL } from '../../utils/url';
import { useUser } from '../../../hooks/react-query/use-user';
import { useIntroducer } from '../../../hooks/react-query/use-introducer';
import CreateIntroducerForm from '../../shared/create-introducer-form';

export type MainLayoutProps = RouteComponentProps & {
  title?: string;
  loginRequired?: boolean;
  introducerRequired?: boolean;
  children?: ReactNode;
};

function MainLayout({
  title,
  loginRequired = true,
  introducerRequired = false,
  location,
  children
}: MainLayoutProps) {
  const { status: userStatus } = useUser();
  const { status: introducerStatus } = useIntroducer(
    introducerRequired && userStatus === 'success'
  );

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

  function renderContent() {
    if (introducerRequired && introducerStatus === 'error')
      return (
        <div className='mx-auto w-full w-full sm:w-4/5 md:w-3/4 lg:w-2/3'>
          <CreateIntroducerForm />
        </div>
      );

    if (
      (introducerRequired && ['indle', 'loading'].includes(introducerStatus)) ||
      (loginRequired && userStatus === 'loading')
    ) {
      return (
        <div>
          <Loader />
        </div>
      );
    }

    return children;
  }

  if (loginRequired && userStatus === 'error')
    return <Redirect to={getLoginRedirectURL(location.pathname, location.search)} />;

  return (
    <>
      <div className='flex h-screen flex-col'>
        <Header isAuthenticated={userStatus === 'success'} />
        <main data-testid='main' className='flex-1 py-4'>
          <Container>{renderContent()}</Container>
        </main>
        <Footer />
      </div>
      <ScrollToTop />
    </>
  );
}

export default withRouter(MainLayout);
