import React, { useState, useEffect } from 'react';

interface GameState {
  n: number;
  boxes: number[];
  currentPrisoner: number;
  openedBoxes: number[];
  foundNumber: boolean;
  gameOver: boolean;
  won: boolean;
  prisonersCompleted: number;
  attemptsLeft: number;
}

const PrisonerGameSimulator: React.FC = () => {
  const [n, setN] = useState(10);
  const [gameState, setGameState] = useState<GameState | null>(null);

  const initializeGame = (numPrisoners: number) => {
    // Create a random permutation
    const boxes = Array.from({ length: numPrisoners }, (_, i) => i + 1);
    for (let i = boxes.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [boxes[i], boxes[j]] = [boxes[j], boxes[i]];
    }

    setGameState({
      n: numPrisoners,
      boxes,
      currentPrisoner: 1,
      openedBoxes: [],
      foundNumber: false,
      gameOver: false,
      won: false,
      prisonersCompleted: 0,
      attemptsLeft: Math.floor(numPrisoners / 2),
    });
  };

  useEffect(() => {
    initializeGame(n);
  }, []);

  const handleBoxClick = (boxIndex: number) => {
    if (!gameState || gameState.gameOver || gameState.openedBoxes.includes(boxIndex)) {
      return;
    }

    const newOpenedBoxes = [...gameState.openedBoxes, boxIndex];
    const numberInBox = gameState.boxes[boxIndex];
    const foundTarget = numberInBox === gameState.currentPrisoner;
    const newAttemptsLeft = gameState.attemptsLeft - 1;

    if (foundTarget) {
      // Prisoner found their number!
      const newPrisonersCompleted = gameState.prisonersCompleted + 1;
      
      if (newPrisonersCompleted === gameState.n) {
        // All prisoners succeeded!
        setGameState({
          ...gameState,
          openedBoxes: newOpenedBoxes,
          foundNumber: true,
          gameOver: true,
          won: true,
          prisonersCompleted: newPrisonersCompleted,
          attemptsLeft: newAttemptsLeft,
        });
      } else {
        // Move to next prisoner
        setGameState({
          ...gameState,
          currentPrisoner: gameState.currentPrisoner + 1,
          openedBoxes: [],
          foundNumber: false,
          prisonersCompleted: newPrisonersCompleted,
          attemptsLeft: Math.floor(gameState.n / 2),
        });
      }
    } else if (newAttemptsLeft === 0) {
      // Ran out of attempts - game over
      setGameState({
        ...gameState,
        openedBoxes: newOpenedBoxes,
        foundNumber: false,
        gameOver: true,
        won: false,
        attemptsLeft: 0,
      });
    } else {
      // Continue opening boxes
      setGameState({
        ...gameState,
        openedBoxes: newOpenedBoxes,
        attemptsLeft: newAttemptsLeft,
      });
    }
  };

  const handleReset = () => {
    initializeGame(n);
  };

  const handleNChange = (newN: number) => {
    setN(newN);
    initializeGame(newN);
  };

  if (!gameState) return null;

  return (
    <div className="my-8 p-6 border-2 border-gray-300 rounded-lg bg-gray-50">
      <div className="mb-6">
        <label className="block text-lg font-semibold mb-2">
          Number of Prisoners: {n}
        </label>
        <input
          type="range"
          min="5"
          max="100"
          value={n}
          onChange={(e) => handleNChange(parseInt(e.target.value))}
          className="w-full h-2 bg-blue-200 rounded-lg appearance-none cursor-pointer"
          disabled={gameState.prisonersCompleted > 0 && !gameState.gameOver}
        />
        <div className="flex justify-between text-sm text-gray-600 mt-1">
          <span>5</span>
          <span>100</span>
        </div>
      </div>

      <div className="mb-4 p-4 bg-blue-100 rounded">
        {!gameState.gameOver && (
          <>
            <p className="text-lg font-semibold">
              Prisoner #{gameState.currentPrisoner} is searching for their number
            </p>
            <p className="text-md">
              Attempts remaining: {gameState.attemptsLeft} / {Math.floor(gameState.n / 2)}
            </p>
            <p className="text-md">
              Prisoners completed: {gameState.prisonersCompleted} / {gameState.n}
            </p>
          </>
        )}
        {gameState.gameOver && gameState.won && (
          <p className="text-2xl font-bold text-green-600">
            🎉 SUCCESS! All {gameState.n} prisoners found their numbers!
          </p>
        )}
        {gameState.gameOver && !gameState.won && (
          <p className="text-2xl font-bold text-red-600">
            ❌ GAME OVER! Prisoner #{gameState.currentPrisoner} failed to find their number.
          </p>
        )}
      </div>

      <div className="mb-4">
        <h3 className="text-md font-semibold mb-2">Click on boxes to open them:</h3>
        <div 
          className="grid gap-2"
          style={{
            gridTemplateColumns: `repeat(${Math.min(10, Math.ceil(Math.sqrt(gameState.n)))}, minmax(0, 1fr))`,
          }}
        >
          {gameState.boxes.map((number, index) => {
            const isOpened = gameState.openedBoxes.includes(index);
            const isTarget = number === gameState.currentPrisoner && isOpened;
            
            return (
              <button
                key={index}
                onClick={() => handleBoxClick(index)}
                disabled={gameState.gameOver || isOpened}
                className={`
                  aspect-square p-2 rounded border-2 font-semibold text-sm
                  transition-all duration-200
                  ${isOpened 
                    ? isTarget 
                      ? 'bg-green-400 border-green-600 text-white'
                      : 'bg-red-200 border-red-400 text-gray-700'
                    : 'bg-white border-gray-400 hover:bg-blue-100 hover:border-blue-500 cursor-pointer'
                  }
                  ${gameState.gameOver || isOpened ? 'cursor-not-allowed' : ''}
                `}
              >
                {isOpened ? (
                  <div className="flex flex-col items-center justify-center h-full">
                    <div className="text-xs">Box {index + 1}</div>
                    <div className="text-lg">{number}</div>
                  </div>
                ) : (
                  <div className="flex items-center justify-center h-full">
                    {index + 1}
                  </div>
                )}
              </button>
            );
          })}
        </div>
      </div>

      <button
        onClick={handleReset}
        className="px-6 py-3 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700 transition-colors"
      >
        Reset Game
      </button>

      {gameState.openedBoxes.length > 0 && !gameState.gameOver && (
        <div className="mt-4 p-3 bg-yellow-100 rounded">
          <p className="text-sm">
            <strong>Last opened:</strong> Box {gameState.openedBoxes[gameState.openedBoxes.length - 1] + 1} 
            {' → '}contains number {gameState.boxes[gameState.openedBoxes[gameState.openedBoxes.length - 1]]}
          </p>
        </div>
      )}
    </div>
  );
};

export default PrisonerGameSimulator;
