import { RedirectLoginOptions, useAuth0 } from "@auth0/auth0-react";
import queryString from "query-string";
import { PropsWithChildren, useEffect } from "react";

interface Props extends PropsWithChildren<any>{
    setToken: React.Dispatch<React.SetStateAction<string | undefined>>
    prevPath?: string
}

export default function AuthWrapper(props: Props) {
  const { children, setToken } = props;
  const { isLoading, loginWithRedirect, isAuthenticated, getAccessTokenSilently } = useAuth0();


  useEffect(() => {
    const url = new URL(window.location.href);

    const isManualLoginPage = url.pathname.includes("/login");

    if (isManualLoginPage) {
      const options: RedirectLoginOptions = {
        authorizationParams: {}  // Initialize here
      };

      let parsed = queryString.parse(url.search);
      if (parsed.signup === "true") {
        options.authorizationParams!.screen_hint = "signup"; 
        options.authorizationParams!.prompt = "login";
      }

      if (parsed.email && parsed.email !== "") {
        options.authorizationParams!.login_hint = parsed.email.toString(); // prefill email
      }
      
      loginWithRedirect(options)

    } else if (!isAuthenticated && !isLoading) {
      loginWithRedirect();
    }
  }, [isAuthenticated, loginWithRedirect, isLoading]);

  useEffect(() => {
    if (isAuthenticated) getAccessTokenSilently().then(t => {
      if (t.length < 1) {
        loginWithRedirect()
      }
      setToken(t)
    }).catch(() => {
      // No token, go back to login
      loginWithRedirect()
    })
  }, [setToken, isAuthenticated])

  return children;
}