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

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

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

const NeosConfig = useConfig();
const DefaultUserName = "Guest";

const Home: React.FC = () => {
  const { user } = useSnapshot(accountStore);
  const navigate = useNavigate();

  const onLogout = () => {}; // TODO
  const onMatchAI = () => {
    const username = user?.username ?? DefaultUserName;
    navigate(
      `/room/${username}/${encodeURIComponent("AI")}/${
        NeosConfig.servers[0].ip
      }:${NeosConfig.servers[0].port}`
    );
  };

  useEffect(() => {
    if (!user) {
      // 跳转SSO界面进行登录
      navigate("/sso");
    }
  }, [user]);

  return (
    <>
      <div className={styles["account-header"]}>
        <a href="https://mycard.moe/">
          <img
            src={`${NeosConfig.assetsPath}/mycard_logo.png`}
            alt="MyCard"
            width={130}
            height={40}
          />
        </a>
        <div className={styles["header-user"]}>
          <img
            src={
              user?.avatar_url ?? `${NeosConfig.assetsPath}/default-avatar.png`
            }
            alt={user?.username}
            height={40}
          />
          <a className={styles["header-user-btn"]} href={NeosConfig.profileUrl}>
            个人中心
          </a>
          <span className={styles.sep}>|</span>
          <a className={styles["header-user-btn"]} href="" onClick={onLogout}>
            登出
          </a>
        </div>
      </div>
      <div className={styles.container}>
        <div className={styles.bg}></div>
        <div className={styles.box}>
          <p>欢迎来到NEOS，{user?.username}</p>
          <button>娱乐匹配</button>
          <button>竞技匹配</button>
          <button onClick={() => navigate("/match")}>自定义匹配</button>
          <button onClick={onMatchAI}>人机对战</button>
          <button onClick={() => navigate("/replay")}>录像回放</button>
          <button>卡组编辑</button>
        </div>
      </div>
    </>
  );
};

export default Home;
