import { Select, Space, ConfigProvider } from "antd";
import classNames from "classnames";
import { type LoaderFunction } from "react-router-dom";

import { accountStore, type User } from "@/stores";
import { Background, CookieKeys, setCookie } from "@/ui/Shared";

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

export const loader: LoaderFunction = () => {
  const sso = new URLSearchParams(location.search).get("sso");
  const user = sso ? getSSOUser(new URLSearchParams(atob(sso))) : undefined;
  if (user) {
    accountStore.login(user);
    setCookie(CookieKeys.USER, JSON.stringify(user));
  }
  return null;
};

export const Component: React.FC = () => {
  return (
    <>
      <Background />
      <main className={styles.main}>
        <div className={styles.container}>
          <Space size={16}>
            <CustomSelect
              title="服务器"
              defaultValue="lucy"
              style={{ width: 370 }}
              options={[
                { value: "jack", label: "Jack" },
                { value: "lucy", label: "Lucy" },
                { value: "Yiminghe", label: "yiminghe" },
                { value: "disabled", label: "Disabled", disabled: true },
              ]}
            />
            <CustomSelect
              title="卡组"
              showSearch
              defaultValue="lucy"
              style={{ width: 370 }}
              options={[
                { value: "jack", label: "Jack" },
                { value: "lucy", label: "Lucy" },
                { value: "Yiminghe", label: "yiminghe" },
                { value: "disabled", label: "Disabled", disabled: true },
              ]}
            />
          </Space>
          <div className={styles["mode-select"]}>
            <div className={classNames(styles.mode, styles.rank)}>竞技匹配</div>
            <div className={classNames(styles.mode, styles.fun)}>娱乐匹配</div>
            <div className={classNames(styles.mode, styles.solo)}>单人模式</div>
            <div className={classNames(styles.mode, styles.custom)}>
              自定义房间
            </div>
          </div>
        </div>
      </main>
    </>
  );
};
Component.displayName = "Match";

/** 从SSO跳转回的URL之中，解析用户信息 */
function getSSOUser(searchParams: URLSearchParams): User {
  return Object.fromEntries(searchParams) as unknown as User;
}

const CustomSelect: React.FC<
  React.ComponentProps<typeof Select> & { title: string }
> = ({ title, className, ...rest }) => {
  return (
    <ConfigProvider
      theme={{
        components: {
          Select: {
            colorBgElevated: "#00132Dff",
            controlItemBgActive: "#00286055",
          },
        },
      }}
    >
      <div className={styles["custom-select"]}>
        <span className={styles.prefix}>{title}</span>
        <Select
          className={classNames(styles.select, className)}
          size="large"
          {...rest}
        />
      </div>
    </ConfigProvider>
  );
};
