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

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

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

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

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

  const onLogout = () => {}; // TODO
  const onMatchAI = () => {
    const username = accountStore.user?.username ?? DefaultUserName;
    navigate(
      `/room/${username}/${encodeURIComponent("AI")}/${
        NeosConfig.servers[0].ip
      }:${NeosConfig.servers[0].port}`
    );
  };
  const onEntertainMatch = async () => {
    // if (user) {
    //   const matchInfo = await match(user.username, user.external_id);
    //   if (matchInfo) {
    //     navigate(
    //       `/room/${user.username}/${encodeURIComponent(matchInfo.password)}/${
    //         matchInfo.address
    //       }:${matchInfo.port}`
    //     );
    //   } else {
    //     alert("匹配失败");
    //   }
    // } else {
    //   alert("请先登录萌卡账号");
    // }

    // TODO: 这部分需要修改后端逻辑，改完后端后再来补充这里
    alert("暂不支持，敬请期待");
  };

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

  return (
    <>
      <div className={styles["account-header"]}>
        <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 onClick={onEntertainMatch}>娱乐匹配</button>
          <button onClick={() => alert("暂不支持，敬请期待")}>竞技匹配</button>
          <button onClick={() => navigate("/match")}>自定义匹配</button>
          <button onClick={onMatchAI}>人机对战</button>
          <button onClick={() => navigate("/replay")}>录像回放</button>
          <button onClick={() => alert("暂不支持，敬请期待")}>卡组编辑</button>
        </div>
      </div>
    </>
  );
};
Component.displayName = "Profile";
