import { CheckCircleFilled } from "@ant-design/icons";

import { ygopro } from "@/api";
import PlayerState = ygopro.StocHsPlayerChange.State;
import { Avatar, Button, ConfigProvider, Popover, Skeleton, Space } from "antd";
import classNames from "classnames";
import React, { useState } from "react";
import { type LoaderFunction, useLoaderData } from "react-router-dom";
import { useSnapshot } from "valtio";

import { useConfig } from "@/config";
import { accountStore, Player, roomStore, type User } from "@/stores";
import { Background, IconFont, Select } from "@/ui/Shared";

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

const NeosConfig = useConfig();

interface Params {
  player?: string;
  passWd?: string;
  ip?: string;
}

export const loader: LoaderFunction = async ({ params }) => params;

const theme = {
  components: {
    Button: {
      lineWidth: 0,
      fontSizeLG: 14,
      fontSize: 12,
      colorBgContainer: "hsla(0, 0%, 100%, 0.05)",
      colorPrimaryHover: "#ccc",
      colorPrimaryActive: "#aaa",
    },
    Popover: {
      colorBgElevated: "hsla(0, 0%, 100%, 0.1)",
    },
  },
};

export const Component: React.FC = () => {
  const _params = useLoaderData<Params>();
  const { user } = useSnapshot(accountStore);
  const [collapsed, setCollapsed] = useState(false);
  const room = useSnapshot(roomStore);
  return (
    <ConfigProvider theme={theme}>
      <div
        className={classNames(styles.container, {
          [styles.collapsed]: collapsed,
        })}
      >
        <Background />
        <div className={styles.sider}>
          <Button
            className={styles["btn-sider"]}
            icon={<IconFont type="icon-side-bar-fill" size={16} />}
            onClick={() => setCollapsed(!collapsed)}
          />

          <Chat />
        </div>
        <div className={styles.main}>
          {/* <div className={styles["status-bar"]}>
            <LoadingOutlined />
            对方正在选择先后
          </div> */}
          <Controller />
          <div className={styles["both-side-container"]}>
            <PlayerZone
              who={Who.Me}
              player={room.getMePlayer()}
              avatar={user?.avatar_url}
              btn={
                <>
                  <Button size="large" className={styles["btn-join"]}>
                    决斗准备
                  </Button>
                </>
              }
            />
            <PlayerZone who={Who.Op} player={room.getOpPlayer()} />
          </div>
        </div>
      </div>
    </ConfigProvider>
  );
};

enum Mora {
  Rock = "rock",
  Scissors = "scissors",
  Paper = "paper",
}

const MoraButton: React.FC<{
  onClick?: () => Promise<Mora>;
}> = () => {
  // TODO: 实现这个onclick
  // 防抖

  const map = {
    [Mora.Rock]: "石头",
    [Mora.Scissors]: "剪刀",
    [Mora.Paper]: "布",
  };

  return (
    <Popover
      overlayStyle={{ backdropFilter: "blur(10px)" }}
      content={
        <Space>
          {[Mora.Rock, Mora.Scissors, Mora.Paper].map((mora) => (
            <Button
              size="large"
              type="text"
              icon={<IconFont type={`icon-hand-${mora}`} size={16} />}
            >
              {map[mora]}
            </Button>
          ))}
        </Space>
      }
      trigger="focus"
      placement="bottom"
    >
      <Button
        size="large"
        className={styles["btn-join"]}
        icon={<IconFont type="icon-mora" size={20} />}
      >
        猜拳
      </Button>
    </Popover>
  );
};

const OrderPopup: React.FC<React.PropsWithChildren<{ open: boolean }>> = ({
  children,
  open,
}) => {
  return (
    <Popover
      overlayStyle={{ backdropFilter: "blur(10px)" }}
      open={open}
      content={
        <Space>
          <Button
            size="large"
            type="text"
            icon={<IconFont type="icon-one" size={18} />}
          >
            先手
          </Button>
          <Button
            size="large"
            type="text"
            icon={<IconFont type="icon-two" size={18} />}
          >
            后手
          </Button>
        </Space>
      }
      trigger="focus"
      placement="bottom"
    >
      {children}
    </Popover>
  );
};

enum Who {
  Me = "me",
  Op = "op",
}

// 玩家区域: 两侧各有一个
const PlayerZone: React.FC<{
  btn?: React.ReactNode; // 在内部右侧可以放一个按钮
  who?: Who;
  player?: Player;
  avatar?: string; // 因为对手的头像目前不清楚如何获取，因此暂时这里作为一个参数传入
}> = ({ btn, who, player, avatar }) => {
  return (
    <div className={classNames(styles["side-box"], who && styles[who])}>
      <div className={styles.inner}></div>
      <OrderPopup open={false}>
        <div style={{ position: "relative" }}>
          <Avatar
            src={avatar ?? `${NeosConfig.assetsPath}/default-avatar.png`}
            size={48}
          />
          {player?.state === PlayerState.READY && (
            <CheckCircleFilled className={styles.check} />
          )}
        </div>
      </OrderPopup>
      <div className={styles.name}>
        {player ? player.name : <Skeleton.Input size="small" />}
      </div>
      {btn}
    </div>
  );
};

const Controller: React.FC = () => {
  return (
    <Space>
      <Select
        title="卡组"
        showSearch
        defaultValue="lucy"
        style={{ width: 300 }}
        options={[
          { value: "jack", label: "Jack" },
          { value: "lucy", label: "Lucy" },
          { value: "Yiminghe", label: "yiminghe" },
          { value: "disabled", label: "Disabled", disabled: true },
        ]}
      />
      <Button size="large" icon={<IconFont type="icon-record" size={18} />}>
        加入观战
        <Avatar.Group className={styles["avatars-watch"]}>
          <Avatar
            src="https://xsgames.co/randomusers/avatar.php?g=pixel&key=1"
            size="small"
          />
          <Avatar style={{ backgroundColor: "#f56a00" }} size="small">
            K
          </Avatar>
          <Avatar style={{ backgroundColor: "#87d068" }} size="small" />
        </Avatar.Group>
      </Button>
      <Button size="large" icon={<IconFont type="icon-play" size={12} />}>
        开始游戏
      </Button>
    </Space>
  );
};
