import React, { ReactElement, useState, useEffect } from "react";
import NotFound from "contexts/NotFound";
import NotFoundPage from "pages/NotFoundPage";

type Props = {
  children?: ReactElement;
};

const PageNotFoundBoundary: React.FC<Props> = (props) => {
  const { children } = props;
  const [hasNotFoundError, setHasNotFoundError] = useState(false);

  const setNotFound = (notFound = true): void => {
    setHasNotFoundError(notFound);
  };

  useEffect(() => {
    // Always reset the "Page Not Found" error after page transition in case we have moved to a
    // valid page.
    const handlePopState = (): void => {
      setNotFound(false);
    };

    window.addEventListener("popstate", handlePopState);

    return (): void => {
      window.removeEventListener("popstate", handlePopState);
    };
  }, []);

  return (
    <NotFound.Provider value={setNotFound}>
      {hasNotFoundError ? <NotFoundPage /> : children}
    </NotFound.Provider>
  );
};

export default PageNotFoundBoundary;