import React, { useEffect } from "react";

interface SSOParams {
  id: string;
  username: string;
  name: string;
  email: string;
  return_sso_url: string;
  token: string;
}

const Sso: React.FC = () => {
  const sso = new URL(location.href).searchParams.get("sso");
  const ssoParams: SSOParams | undefined = sso
    ? getSSOParams(new URLSearchParams(atob(sso)))
    : undefined;

  useEffect(() => {
    if (!sso) {
      const ssoUrl = getSSOUrl(location.href);

      window.location.href = ssoUrl;
    }
  }, []);

  return (
    <div>
      <p>username={ssoParams?.username}</p>
      <p>name={ssoParams?.name}</p>
      <p>email={ssoParams?.email}</p>
    </div>
  );
};

function getSSOUrl(callbackUrl: string): string {
  let params = new URLSearchParams();
  params.set("return_sso_url", callbackUrl);
  const payload = btoa(params.toString());

  const url = new URL("https://accounts.moecube.com");
  params = url.searchParams;
  params.set("sso", payload);

  return url.toString();
}

function getSSOParams(searchParams: URLSearchParams): SSOParams {
  const sso = {};
  for (const [key, value] of searchParams) {
    // @ts-ignore
    sso[key] = value;
  }

  return sso as any;
}

export default Sso;
