import React, { useEffect, useState } from "react";

import { match, MatchInfo } from "@/api";

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

const Sso: React.FC = () => {
  const sso = new URL(location.href).searchParams.get("sso");
  const ssoParams: SSOParams | undefined = sso
    ? getSSOParams(new URLSearchParams(atob(sso)))
    : undefined;
  const [matchInfo, setMatchInfo] = useState<MatchInfo | undefined>(undefined);
  const onMatch = async () => {
    if (ssoParams) {
      setMatchInfo(await match(ssoParams.username, ssoParams.external_id));
    }
  };

  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>
      <button onClick={onMatch}>match</button>
      <p>match info</p>
      <p>address={matchInfo?.address}</p>
      <p>port={matchInfo?.port}</p>
      <p>password={matchInfo?.password}</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;
