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

import { useConfig } from "@/config";
import { accountStore, User } from "@/stores";

const NeosConfig = useConfig();

const SSO: React.FC = () => {
  const sso = new URL(location.href).searchParams.get("sso");
  const user: User | undefined = sso
    ? getSSOUser(new URLSearchParams(atob(sso)))
    : undefined;

  const [logined, setLogined] = useState(false);

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

      window.location.href = ssoUrl;
    }

    if (user) {
      accountStore.login(user);
      setLogined(true);
      // TODO: navigate
    }
  }, []);

  return (
    <div>
      <p>{logined ? "登录成功，正在跳转。。" : "登录萌卡账号中。。。"}</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(NeosConfig.accountUrl);
  params = url.searchParams;
  params.set("sso", payload);

  return url.toString();
}

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

  return sso as any;
}

export default SSO;
