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

import { CookieKeys, getCookie } from "@/api";
import { useConfig } from "@/config";
import { accountStore, deckStore, initStore, type User } from "@/stores";

import styles from "./index.module.scss";
import { initSqlite } from "./utils";

const NeosConfig = useConfig();

export const loader: LoaderFunction = async () => {
  const user = getCookie<User>(CookieKeys.USER);
  if (user) accountStore.login(user);
  // 加载卡组
  if (!initStore.decks)
    deckStore.initialize().then(() => (initStore.decks = true));
  // 加载ygodb
  if (!initStore.sqlite.progress) {
    initSqlite().then(() => (initStore.sqlite.progress = 1));
    initStore.sqlite.progress = 0.01;
  }
  return null;
};

export const Component = () => {
  // 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>
          {/* <img
          className={styles.logo}
          src={`${NeosConfig.assetsPath}/neos-logo.svg`}
          alt="NEOS"
        /> */}
          <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} />;
};
