import { Avatar } from "antd";
import { useEffect } from "react";
import {
  type LoaderFunction,
  NavLink,
  Outlet,
  useLocation,
} from "react-router-dom";
import { useSnapshot } from "valtio";

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

import styles from "./index.module.scss";
import {
  getLoginStatus,
  handleSSOLogin,
  initDeck,
  initSqlite,
  initWASM,
} from "./utils";

const NeosConfig = useConfig();

export const loader: LoaderFunction = async () => {
  getLoginStatus();
  initDeck();
  initSqlite();
  initWASM();
  return null;
};

export const Component = () => {
  // 捕获SSO登录
  const location = useLocation();
  useEffect(() => {
    location.search && handleSSOLogin(location.search);
  }, [location.search]);

  // TODO 根据是否登录，显示内容
  const { pathname } = useLocation();
  const pathnamesHideHeader = ["/waitroom"];
  return (
    <>
      {!pathnamesHideHeader.includes(pathname) && (
        <nav className={styles.navbar}>
          <div className={styles["logo-container"]}>
            <img
              className={styles.logo}
              src={`${NeosConfig.assetsPath}/neos-logo.svg`}
              alt="NEOS"
            />
          </div>
          <NavLink to="/">主页</NavLink>
          <NavLink to="/match">匹配</NavLink>
          <NavLink to="/build">组卡</NavLink>
          <span style={{ flexGrow: 1 }} />
          <span className={styles.profile}>
            <NeosAvatar />
            <NavLink to="/profile">个人中心</NavLink>
          </span>
        </nav>
      )}
      <main className={styles.main}>
        <Outlet />
      </main>
    </>
  );
};

const NeosAvatar = () => {
  const { user } = useSnapshot(accountStore);
  return <Avatar size="small" src={user?.avatar_url} />;
};
