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, 
    // getIdTokenClaims 
  } = useAuth0();


  useEffect(() => {
    const url = new URL(window.location.href);
    const isManualLoginPage = url.pathname.includes("/login");
    const options: RedirectLoginOptions = {
      authorizationParams: {}  // Initialize here
    };

    if (isManualLoginPage && options.authorizationParams) {
      
      let parsed = queryString.parse(url.search);
      if (parsed.signup === "true") {
        options.authorizationParams.screen_hint = "signUp"; 
        // options.authorizationParams.m
        // options.authorizationParams.prompt = "login";
      }

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

      console.log(url)
      options.authorizationParams.redirect_uri = url.origin + "/signupCallback"
      console.log(options.authorizationParams.redirect_uri)
      
      loginWithRedirect(options)

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

  useEffect(() => {
    // const url = new URL(window.location.href);
    // const isSignupCallback = url.pathname.includes("/signupCallback");
    if (isAuthenticated) {
      getAccessTokenSilently().then(t => {
        if (t.length < 1) {
          loginWithRedirect()
        }
        setToken(t)
      }).catch(() => {
        // No token, go back to login
        loginWithRedirect()
      })
      // if (isSignupCallback) {
      //   getIdTokenClaims().then(id_claims => {
      //     console.log(id_claims)
      //     console.log(id_claims?.nickname)
      //     if (id_claims) console.log(Object.keys(id_claims))
      //   })
      // }
      
    }
  }, [setToken, isAuthenticated])

  return children;
}