import CSMessage from "@/Common/Message/CSMessage";
import { CoroutineV2 } from "@/Engine/CatanEngine/CoroutineV2/CoroutineV2";
import { INetResponse } from "@/Engine/CatanEngine/NetManagerV2/Core/INetResponse";
import CSSettingsSDV3 from "@/FormTableSD/CSSettingsSDV3";
import BusinessTypeSetting, { BusinessEnum } from "@/_BusinessTypeSetting/BusinessTypeSetting";
import Image from "@/components/Image/Image";
import { useGameItems } from "@/context/GameItemsContext";
import { GameLaunchRequest, GameLeaveRequest, RpcGameLaunchResponse } from "@/define/Request/GameRequest";
import { SlotData } from "@/define/gameData";
import GameManager from "@/modules/GameManager";
import { Button, Empty } from "antd";
import React, { useEffect, useState } from "react";
import SDGame from "./SDGame";

/** 取得目前環境對應的 SD compony ID */
function getSDType(): number {
	const UseServerType = BusinessTypeSetting.UseServerType;
	const ServerType = BusinessEnum.ServerType[UseServerType];
	return BusinessEnum.ComponyType[ServerType];
}

const SlotList = () => {
	const { gameData, setGameData } = useGameItems();
	const { slotData, slotList, nowSlotId } = gameData;
	const [isGameIn, setIsGameIn] = useState<boolean>(false);
	const [gameUrl, setGameUrl] = useState<string>("");

	function onLoad() {

	}

	function* onClickSlotIn(slotId: number): IterableIterator<any> {
		const data: SlotData = slotData[slotId];
		const [componyID] = data;
		const req: GameLaunchRequest = new GameLaunchRequest(componyID, slotId);
		yield req.SendAsync();
		const resp: INetResponse<RpcGameLaunchResponse> = req.Result;
		if (!resp.IsValid) {
			if (resp.Status === 18) {
				CSMessage.CreateYesMsg(CSSettingsSDV3.prototype.CommonString(16));
			}
			return;
		}
		setIsGameIn(true);
		GameManager.IsInGame = true;
		const url: string = resp.Data;
		setGameData({
			...gameData,
			nowSlotId: slotId
		});
		console.log(`[SlotIn] slot:${slotId} componyID:${componyID} SDType:${getSDType()} → ${componyID === getSDType() ? "SD面板" : "開新視窗"}`);
		if (componyID === getSDType()) {
			setGameUrl(url);
		}
		else {
			window.open(url, "_blank");
		}
	}

	function onClickSlotOut() {
		const gameLeaveReq: GameLeaveRequest = new GameLeaveRequest(nowSlotId);
		gameLeaveReq.Send();
		setGameUrl("");
		setIsGameIn(false);
		GameManager.IsInGame = false;
	}

	useEffect(() => {
		onLoad();
	}, []);

	// 遊戲中：SD 開自製 Spin 面板，其餘顯示外開視窗提示
	if (isGameIn) {
		if (gameUrl) {
			return <SDGame gameUrl={gameUrl} onClickSlotOut={onClickSlotOut} />;
		}
		return (
			<div className="lp-panel lp-corners lp-rise" style={externalStyle}>
				<div className="lp-kicker" style={{ marginBottom: 10 }}>External Game</div>
				<h2 className="lp-title" style={{ fontSize: 22, marginBottom: 6 }}>機台 {nowSlotId} 已於新視窗開啟</h2>
				<p style={{ color: "var(--lp-text-dim)", margin: "0 0 24px" }}>結束遊戲後請點擊下方按鈕離開機台。</p>
				<Button danger type="primary" size="large" onClick={onClickSlotOut} style={{ minWidth: 160 }}>
					離開機台
				</Button>
			</div>
		);
	}

	// 機台清單
	return (
		<div style={wrapStyle} className="lp-rise">
			<div style={headRowStyle}>
				<span className="lp-kicker">Machines</span>
				<span className="lp-label">共 {slotList.length} 台</span>
			</div>
			<div style={gridStyle}>
				{slotList.length === 0 &&
					<Empty description={<span style={{ color: "var(--lp-text-dim)" }}>等待機台清單同步...</span>} style={{ margin: "auto" }} />
				}
				{slotList.map((slotId: number, index: number) => {
					const isSD: boolean = slotData[slotId]?.[0] === getSDType();
					return (
						<div key={index} className="lp-slot-card" style={{ animationDelay: `${Math.min(index * 0.02, 0.4)}s` }}
							onClick={() => { CoroutineV2.Single(onClickSlotIn(slotId)).Start(); }}>
							{isSD && <span className="lp-slot-badge">SD</span>}
							<Image src={`${BusinessTypeSetting.UseDownloadUrl}vendor_game/${slotId}/s`} />
							<div className="lp-slot-id">#{slotId}</div>
						</div>
					);
				})}
			</div>
		</div>
	);
};

export default SlotList;

const wrapStyle: React.CSSProperties = {
	flex: 1,
	minHeight: 0,
	display: "flex",
	flexDirection: "column",
};

const headRowStyle: React.CSSProperties = {
	display: "flex",
	alignItems: "center",
	justifyContent: "space-between",
	marginBottom: 12,
};

const gridStyle: React.CSSProperties = {
	flex: 1,
	minHeight: 0,
	overflowY: "auto",
	display: "flex",
	flexWrap: "wrap",
	alignContent: "flex-start",
	gap: 12,
	paddingBottom: 12,
};

const externalStyle: React.CSSProperties = {
	margin: "auto",
	maxWidth: 440,
	width: "100%",
	padding: "36px 36px 32px",
	textAlign: "center",
};
