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

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

  const renderHistory = () => {
    if (!gameState.gameHistory || gameState.gameHistory.length === 0) {
      return <div className="empty-history">No games yet.</div>;
    }

    return (
      <div className="history-list">
        {gameState.gameHistory.map((game, index) => (
          <div 
            key={game.id} 
            className="history-item"
            onClick={() => {
              // Would load game details
              setCurrentScreen('setup');
            }}
          >
            <h3>{game.players.length} players, {game.rounds.length} rounds</h3>
            <div className="history-date">
              {new Date(game.date).toLocaleDateString()}
            </div>
            <div className="history-scores">
              {Object.entries(game.finalScores).map(([playerId, score]) => (
                <span key={playerId} className="score-tag">
                  {game.players.find(p => p.id === playerId)?.name}: {score}
                </span>
              ))}
            </div>
          </div>
        ))}
      </div>
    );
  };

  const exportData = () => {
    const dataStr = JSON.stringify(gameState.gameHistory, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
    
    const exportFileDefaultName = 'tschausepp-history.json';
    
    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
  };

  const clearHistory = () => {
    if (window.confirm('Are you sure you want to clear all game history?')) {
      // This would normally be handled by the hook, but we're doing it manually for demo
      localStorage.removeItem('tschausepp_game_state');
      window.location.reload();
    }
  };

  return (
    <div className="screen history-screen">
      <h1>📚 Game History</h1>
      {renderHistory()}
      
      <div className="history-actions">
        <button onClick={exportData} className="secondary">
          Export History
        </button>
        <button onClick={clearHistory} className="secondary">
          Clear History
        </button>
        <button onClick={() => setCurrentScreen('setup')} className="primary">
          Back to Setup
        </button>
      </div>
    </div>
  );
};

export default HistoryScreen;