import { useState, useEffect } from 'react';
import { GameState, Game, Player, Card } from '../types';

const useGameState = () => {
  const [gameState, setGameState] = useState<GameState>(() => {
    const savedState = localStorage.getItem('tschausepp_game_state');
    if (savedState) {
      return JSON.parse(savedState);
    }
    return {
      currentScreen: 'setup',
      players: [
        { id: '1', name: 'Player 1' },
        { id: '2', name: 'Player 2' }
      ],
      cardValues: {
        Schellen: 11,
        Schilten: 12,
        Eicheln: 10,
        Rosen: 10
      },
      currentRound: 1,
      detectedCards: [],
      gameHistory: [],
      cameraStream: null
    };
  });

  useEffect(() => {
    const stateToSave = {
      ...gameState,
      cameraStream: null,
    };
    localStorage.setItem('tschausepp_game_state', JSON.stringify(stateToSave));
  }, [gameState]);

  const updatePlayers = (players: Player[]) => {
    setGameState(prev => ({ ...prev, players }));
  };

  const updateCardValues = (cardValues: Record<'Schellen' | 'Schilten' | 'Eicheln' | 'Rosen', number>) => {
    setGameState(prev => ({ ...prev, cardValues }));
  };

  const addPlayer = (name: string) => {
    setGameState(prev => ({
      ...prev,
      players: [...prev.players, { id: Date.now().toString(), name }]
    }));
  };

  const setCurrentScreen = (screen: GameState['currentScreen']) => {
    setGameState(prev => ({ ...prev, currentScreen: screen }));
  };

  const startNewGame = () => {
    setGameState(prev => ({
      ...prev,
      currentRound: 1,
      detectedCards: [],
      currentScreen: 'camera'
    }));
  };

  const endRound = () => {
    setGameState(prev => ({
      ...prev,
      currentRound: prev.currentRound + 1,
      detectedCards: []
    }));
  };

  const setCameraStream = (stream: MediaStream | null) => {
    setGameState(prev => ({ ...prev, cameraStream: stream }));
  };

  const saveGame = (game: Game) => {
    setGameState(prev => {
      const updatedHistory = [...prev.gameHistory, game].slice(-100); // Keep only last 100 games
      return {
        ...prev,
        gameHistory: updatedHistory,
        currentScreen: 'setup'
      };
    });
  };

  const scanTable = (detectedCards: Card[]) => {
    setGameState(prev => ({
      ...prev,
      detectedCards
    }));
  };

  const showResults = () => {
    setGameState(prev => ({
      ...prev,
      currentScreen: 'results'
    }));
  };

  return {
    gameState,
    updatePlayers,
    updateCardValues,
    addPlayer,
    setCurrentScreen,
    startNewGame,
    endRound,
    setCameraStream,
    saveGame,
    scanTable,
    showResults
  };
};

export default useGameState;