import { App, List, Modal } from "antd";
import React, { useState } from "react";
import useWebSocket, { ReadyState } from "react-use-websocket";
import { proxy, useSnapshot } from "valtio";

import { useConfig } from "@/config";

const { athleticWatchUrl } = useConfig();

interface Info {
  event: "init" | "create" | "update" | "delete";
  data: Room | Room[] | string;
}

interface Room {
  id?: string;
  title?: string;
  users?: { username: string; position: number }[];
  options: Options;
}

interface Options {
  mode: number;
  rule: number;
  start_lp: number;
  start_lp_tag: number;
  start_hand: number;
  draw_count: number;
  duel_rule: number;
  no_check_deck: boolean;
  no_shuffle_deck: boolean;
  lflist?: number;
  time_limit?: number;
  auto_death: boolean;
}

const localStore = proxy({
  open: false,
});

export const WatchModal: React.FC = () => {
  const { open } = useSnapshot(localStore);
  const [rooms, setRooms] = useState<Room[]>([]);
  const { message } = App.useApp();
  const url = new URL(athleticWatchUrl);
  url.searchParams.set("filter", "started");

  const { readyState } = useWebSocket(url.toString(), {
    onMessage: (event) => {
      const info: Info = JSON.parse(event.data);

      switch (info.event) {
        case "init": {
          //@ts-ignore
          const rooms: Room[] = info.data;
          setRooms(rooms);
          break;
        }
        case "create": {
          //@ts-ignore
          const room: Room = info.data;
          setRooms((prev) => prev.concat(room));
          break;
        }
        case "update": {
          //@ts-ignore
          const room: Room = info.data;
          setRooms((prev) => {
            const target = prev.find((item) => item.id === room.id);
            if (target) {
              Object.assign(target, info.data);
            }
            return prev;
          });
          break;
        }
        case "delete": {
          //@ts-ignore
          const id: string = info.data;
          setRooms((prev) => {
            prev.splice(
              prev.findIndex((room) => room.id === id),
              1,
            );
            return prev;
          });
          break;
        }
      }
    },
    onError: (_e) => message.error("Websocket Error!"),
  });

  return (
    <Modal
      title="观看回放"
      open={open}
      centered
      footer={<></>}
      onCancel={() => (localStore.open = false)}
    >
      <List
        itemLayout="vertical"
        loading={readyState === ReadyState.CONNECTING}
        size="small"
        pagination={{
          position: "bottom",
          align: "center",
          pageSize: 5,
          simple: true,
        }}
        dataSource={rooms}
        renderItem={(room) => (
          <List.Item key={room.id}>
            <List.Item.Meta
              title={`${room.users?.at(0)?.username}与${room.users?.at(1)
                ?.username}的决斗`}
            />
          </List.Item>
        )}
      />
    </Modal>
  );
};

export const watchOpen = () => (localStore.open = true);
