import { method, registerCustomElement } from "ojs/ojvcomponent";
import { h } from "preact";
import { useState } from "preact/hooks";
import { useEffect } from "preact/hooks";
import Context = require("ojs/ojcontext");
import { Footer } from "./footer";
import { Header } from "./header";
import { Content } from "./content/index";
import { Provider } from "react-redux";
import { store } from "../state/store";

type Props = Readonly<{
  appName?: string;
  userLogin?: string;
}>;

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 login = () => {
  const state = crypto.randomUUID();
  const nonce = crypto.randomUUID();
  sessionStorage.setItem("oauth", JSON.stringify({ state, nonce }));
  window.location.href = "https://idcs-25070016ce0c4eb8b6eea18f07fe170d.identity.oraclecloud.com/oauth2/v1/authorize" +
    "?client_id=4e728d65cf5b482ea81e56bf23a9ad8a" +
    "&response_type=code" +
    "&redirect_uri=https%3A%2F%2Flocalhost%3A8000" +
    "&scope=openid" +
    `&nonce=${nonce}` +
    `&state=${state}`;
};

export const App = registerCustomElement(
  "app-root",
  ({ appName = "App Name" }: Props) => {
    const [userLogin, setUserLogin] = useState("");

    useEffect(() => {
      Context.getPageContext().getBusyContext().applicationBootstrapComplete();

      const searchParams = new URLSearchParams(window.location.search);
      if (searchParams.has("code") && searchParams.has("state")) {
        const { state } = 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://idcs-25070016ce0c4eb8b6eea18f07fe170d.identity.oraclecloud.com/oauth2/v1/token", {
          method: "POST",
          headers: new Headers({
            Authorization: "Basic NGU3MjhkNjVjZjViNDgyZWE4MWU1NmJmMjNhOWFkOGE6ZGM1NDdkYmUtOGQ0Yi00MTU1LWEzNzgtZjNhMDNkNTZhNjU0",
            "Content-Type": "application/x-www-form-urlencoded"
          }),
          body: new URLSearchParams({
            grant_type: "authorization_code",
            code
          })
        })
          .then(response => response.json())
          .then(body => {
            const idToken = parseJwt(body.id_token);
            setUserLogin(idToken.user_displayname);
          })
          .finally(() => sessionStorage.removeItem("oauth"));
        // Clear the search parameter from the url
        window.history.pushState({}, document.title, window.location.pathname);
      } else {
        sessionStorage.removeItem("oauth");
      }
    }, []);

    return (
      <Provider store={store}>
        <div id="appContainer" class="oj-web-applayout-page">
          <Header
            appName={appName}
            userLogin={userLogin}
            login={login}
          />
          <Content />
          <Footer />
        </div>
      </Provider>
    );
  }
);
