import React, { useEffect, useState } from "react";
import styled from "styled-components";
import colors from "@theme/colors";
import breakpoints from "@theme/breakpoints";
import AdminHeader from "@components/AdminHeader";
import AdminSidebar from "@components/AdminSidebar";
import { isAuthenticated } from "@utils/auth";
import { useRouter } from "next/router";
import LoadingView from "./LoadingView";

const Main = styled.main`
  display: flex;
  color: ${colors.white};
  background-color: ${colors.darkBlue};
  flex-flow: row nowrap;
  justify-content: flex-start;
  align-items: flex-start;
  flex: 1;

  h1 {
    margin-top: 0;
  }

  & > div {
    padding: 0 1rem;
    width: 100%;
    max-width: 1000px;
    margin: 0 auto;
  }

  @media screen and (max-width: ${breakpoints.mobile}) {
    flex-flow: column nowrap;

    & > nav {
      width: 100%;
    }
  }
`;

const useShouldRedirect = (enabled = true) => {
  const [redirecting, setRedirect] = useState(false);
  const [completed, setCompleted] = useState(!enabled);

  useEffect(() => {
    if (enabled) {
      isAuthenticated().then((result) => {
        setRedirect(!result);
        setCompleted(true);
      });
    }
  }, [enabled]);

  return {
    redirecting,
    completed,
  };
};

type PageProps = {
  requiresAuthentication: boolean;
};

const AdminPageWrapper: React.FC<PageProps> = ({ requiresAuthentication, children }) => {
  const router = useRouter();
  const { completed, redirecting } = useShouldRedirect(requiresAuthentication);

  const { pathname } = router;

  if (redirecting) {
    const loginURL = `/admin/login?next=${pathname}`;
    router.push(loginURL);
  }

  if (!completed) {
    return <LoadingView />;
  }

  return (
    <>
      <AdminHeader />
      <Main>
        <AdminSidebar path={pathname} />
        {children}
      </Main>
    </>
  );
};

export default AdminPageWrapper;
