import React from 'react';
import { GameState } from '../../types';
import { useGameStateContext } from '../../context/GameStateContext';

const ResultsScreen: React.FC = () => {
  const { 
    gameState, 
    saveGame, 
    setCurrentScreen 
  } = useGameStateContext();

  const calculateScores = () => {
    // Scoring logic based on card values
    const scores: Record<string, number> = {};
    
    gameState.players.forEach(player => {
      scores[player.id] = 0;
    });
    
    // Assign cards to players with proper scoring
    gameState.detectedCards.forEach(card => {
      // Use the assignedTo property if available, otherwise distribute randomly
      const player = card.assignedTo 
        ? gameState.players.find(p => p.id === card.assignedTo)
        : gameState.players[Math.floor(Math.random() * gameState.players.length)];
      
      if (player) {
        scores[player.id] += card.value || 10; // Default to 10 points if not set
      }
    });
    
    return scores;
  };

  const scores = calculateScores();
  const highScore = Math.max(...Object.values(scores));

  const handleSaveGame = () => {
    // Create game object for saving
    const game = {
      id: Date.now().toString(),
      date: new Date().toISOString(),
      players: gameState.players,
      rounds: [
        {
          id: Date.now().toString(),
          cards: gameState.detectedCards,
          piles: {}
        }
      ],
      finalScores: scores
    };
    
    saveGame(game);
  };

  const handleNextRound = () => {
    setCurrentScreen('camera');
  };

  return (
    <div className="screen results-screen">
      <h2>🔍 Round Results</h2>
      
      <div className="results-container">
        {gameState.players.map(player => (
          <div key={player.id} className="player-result">
            <h3>{player.name}</h3>
            <div className="score">
              <span className="points">{scores[player.id] || 0} pts</span>
              {scores[player.id] === highScore && (
                <span className="high-score">🏆 High Score</span>
              )}
            </div>
          </div>
        ))}
        
        <div className="cards-summary">
          <h3>Detected Cards</h3>
            <div className="cards-grid">
              {gameState.detectedCards.map(card => (
                <div key={card.id} className="card-preview">
                  <div className="card-suit">
                    {card.suit === 'Schellen' && '🔔'}
                    {card.suit === 'Schilten' && '🛡️'}
                    {card.suit === 'Eicheln' && '🌰'}
                    {card.suit === 'Rosen' && '🌹'}
                  </div>
                  <div className="card-value">{card.value || '?'}pts</div>
                </div>
              ))}
            </div>
        </div>
      </div>
      
      <div className="results-buttons">
        <button onClick={handleNextRound} className="primary">
          Next Round
        </button>
        <button onClick={handleSaveGame} className="secondary">
          End Game & Save
        </button>
        <button onClick={() => setCurrentScreen('setup')} className="secondary">
          Cancel
        </button>
      </div>
    </div>
  );
};

export default ResultsScreen;