import { h, render } from 'preact';
import { signal, computed } from '@preact/signals-core';
import { useEffect, useState, useCallback } from 'preact/hooks';
import Phaser from 'phaser';
import { createGameContext } from 'boardgame-core';
import { GameUI, PromptDialog, CommandLog, createPromptHandler } from 'boardgame-phaser';
import { createInitialState, registry, type TicTacToeState } from './game/tic-tac-toe';
import { GameScene } from './scenes/GameScene';
import './style.css';

const gameContext = createGameContext<TicTacToeState>(registry, createInitialState);

const commandLog = signal<Array<{ input: string; result: string; timestamp: number }>>([]);

// Single PromptHandler — the only consumer of promptQueue
let promptHandler: ReturnType<typeof createPromptHandler> | null = null;
const promptSignal = signal<import('boardgame-core').PromptEvent | null>(null);

// 记录命令日志的辅助函数
function logCommand(input: string, result: { success: boolean; result?: unknown; error?: string }) {
  commandLog.value = [
    ...commandLog.value,
    {
      input,
      result: result.success ? `OK: ${JSON.stringify(result.result)}` : `ERR: ${result.error}`,
      timestamp: Date.now(),
    },
  ];
}

function App() {
  const [phaserReady, setPhaserReady] = useState(false);
  const [game, setGame] = useState<Phaser.Game | null>(null);
  const [scene, setScene] = useState<GameScene | null>(null);
  const [gameState, setGameState] = useState<TicTacToeState | null>(null);

  useEffect(() => {
    const phaserConfig: Phaser.Types.Core.GameConfig = {
      type: Phaser.AUTO,
      width: 560,
      height: 560,
      parent: 'phaser-container',
      backgroundColor: '#f9fafb',
      scene: [],
    };

    const phaserGame = new Phaser.Game(phaserConfig);
    // 通过 init 传递 gameContext
    const gameScene = new GameScene();
    phaserGame.scene.add('GameScene', gameScene, true, { gameContext });

    setGame(phaserGame);
    setScene(gameScene);
    setPhaserReady(true);

    return () => {
      phaserGame.destroy(true);
    };
  }, []);

  useEffect(() => {
    if (phaserReady && scene) {
      // Initialize the single PromptHandler
      promptHandler = createPromptHandler({
        commands: gameContext.commands,
        onPrompt: (prompt) => {
          promptSignal.value = prompt;
          // Also update the scene's prompt reference
          scene.promptSignal.current = prompt;
        },
        onCancel: () => {
          promptSignal.value = null;
          scene.promptSignal.current = null;
        },
      });
      promptHandler.start();

      // Wire the scene's submit function to this PromptHandler
      scene.setSubmitPrompt((cmd: string) => {
        const error = promptHandler!.submit(cmd);
        if (error === null) {
          logCommand(cmd, { success: true });
          promptSignal.value = null;
          scene.promptSignal.current = null;
        } else {
          logCommand(cmd, { success: false, error });
        }
        return error;
      });

      // 监听状态变化
      const dispose = gameContext.state.subscribe(() => {
        setGameState({ ...gameContext.state.value });
      });

      // 运行游戏设置
      gameContext.commands.run('setup').then(result => {
        logCommand('setup', result);
      });

      return () => {
        dispose();
        promptHandler?.destroy();
        promptHandler = null;
      };
    }
  }, [phaserReady, scene]);

  const handlePromptSubmit = useCallback((input: string) => {
    if (promptHandler) {
      promptHandler.submit(input);
    }
  }, []);

  const handlePromptCancel = useCallback(() => {
    if (promptHandler) {
      promptHandler.cancel('User cancelled');
    }
  }, []);

  const handleReset = useCallback(() => {
    gameContext.commands.run('reset').then(result => {
      logCommand('reset', result);
    });
  }, []);

  return (
    <div className="flex flex-col h-screen">
      <div className="flex-1 relative">
        <div id="phaser-container" className="w-full h-full" />
        
        {/* 游戏状态显示 */}
        {gameState && !gameState.winner && (
          <div className="absolute top-4 left-1/2 transform -translate-x-1/2 bg-white px-4 py-2 rounded-lg shadow-lg z-10">
            <span className="text-lg font-semibold text-gray-800">
              {gameState.currentPlayer}'s Turn
            </span>
          </div>
        )}
        
        {gameState?.winner && (
          <div className="absolute top-4 left-1/2 transform -translate-x-1/2 bg-white px-4 py-2 rounded-lg shadow-lg z-10">
            <span className="text-lg font-semibold text-yellow-600">
              {gameState.winner === 'draw' ? "It's a Draw!" : `${gameState.winner} Wins!`}
            </span>
          </div>
        )}

        <PromptDialog
          prompt={promptSignal.value}
          onSubmit={handlePromptSubmit}
          onCancel={handlePromptCancel}
        />
      </div>
      <div className="p-4 bg-gray-100 border-t">
        <div className="flex justify-between items-center mb-2">
          <span className="text-sm font-medium text-gray-700">Command Log</span>
          <button
            className="px-3 py-1 text-xs font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700"
            onClick={handleReset}
          >
            Reset Game
          </button>
        </div>
        <CommandLog entries={commandLog} />
      </div>
    </div>
  );
}

const ui = new GameUI({
  container: document.getElementById('ui-root')!,
  root: <App />,
});

ui.mount();
