import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

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

import styles from "./index.module.scss";

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);
  const navigate = useNavigate();

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

      window.location.href = ssoUrl;
    }

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

  return (
    <div>
      <p className={styles.hint}>
        {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;
