import { useEffect, useMemo, useState } from "preact/hooks";

const parseJwt = token => {
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(
      c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
    ).join(''));
    return JSON.parse(jsonPayload);
  };
  
  // const idcsStripe = "https://idcs-25070016ce0c4eb8b6eea18f07fe170d.identity.oraclecloud.com";
  const idcsStripe = "https://idcs-login-stage.identity.oraclecloud.com";
  // const clientId = "4e728d65cf5b482ea81e56bf23a9ad8a";
  const clientId = "754db2d1964d4f12ab312a2ab6f025ed";
  
  const login = () => {
    const state = crypto.randomUUID();
    const nonce = crypto.randomUUID();
    sessionStorage.setItem("oauth", JSON.stringify({ state, nonce }));
    window.location.href = `${idcsStripe}/oauth2/v1/authorize` +
      `?client_id=${clientId}` +
      "&response_type=code" +
      `&redirect_uri=${encodeURIComponent(window.location.href)}` +
      "&scope=openid" +
      `&nonce=${nonce}` +
      `&state=${state}`;
  };
  
  const logout = (token: string) => () => {
    // fetch(
    //   `https://idcs-25070016ce0c4eb8b6eea18f07fe170d.identity.oraclecloud.com/oauth2/v1/userlogout?post_logout_redirect_uri=${encodeURIComponent(window.location.origin)}&id_token_hint=${token}`,
    //   // `https://idcs-25070016ce0c4eb8b6eea18f07fe170d.identity.oraclecloud.com/sso/v1/user/logout?post_logout_redirect_uri=${encodeURIComponent(window.location.origin)}&id_token_hint=${token}`,
    //   // `https://idcs-25070016ce0c4eb8b6eea18f07fe170d.identity.oraclecloud.com/oauth2/v1/userlogout?id_token_hint=${token}`,
    //   // `${idcsStripe}/oauth2/v1/userlogout`,
    //   {
    //     headers: {
    //       "Content-Type": "application/scim+json",
    //       // Authorization: `Bearer ${accessToken}`
    //       // Authorization: "Basic NGU3MjhkNjVjZjViNDgyZWE4MWU1NmJmMjNhOWFkOGE6ZGM1NDdkYmUtOGQ0Yi00MTU1LWEzNzgtZjNhMDNkNTZhNjU0"
    //     }
    //   }
    // );
    window.location.href = `${idcsStripe}/sso/v1/user/logout`;
  }

export const useLogin = () => {
    const [userLogin, setUserLogin] = useState("");
    const [accessToken, setAccessToken] = useState("");
    const [idToken, setIdToken] = useState("");

    useEffect(() => {
        const searchParams = new URLSearchParams(window.location.search);
      if (searchParams.has("code") && searchParams.has("state")) {
        const { state, nonce } = JSON.parse(sessionStorage.getItem("oauth"));
        const receivedState = searchParams.get("state");
        if (receivedState !== state) {
          return;
        }
        // Get the tokens using the received authorization code
        const code = searchParams.get("code");
        console.log("code", code);
        fetch("https://localhost/occ/api/auth/login", {
          method: "POST",
          headers: new Headers({
            "Content-Type": "application/json"
          }),
          body: JSON.stringify({ code, nonce })
        })
          .then(response => response.json())
          .then(body => {
            const idToken = parseJwt(body.idToken);
            setUserLogin(idToken.user_displayname);
            setIdToken(body.idToken);
            setAccessToken(body.accessToken);
            console.log("Tokens:", { idToken, accessToken: parseJwt(body.accessToken) })
          })
          .finally(() => sessionStorage.removeItem("oauth"));
        // Clear the search parameter from the url
        window.history.pushState({}, document.title, window.location.pathname);
      } else {
        sessionStorage.removeItem("oauth");
      }
    }, []);

    return {
        userLogin,
        idToken,
        accessToken,
        login,
        logout: logout(idToken)
    };
};