import { create } from 'zustand'
import type { TrackedGame, TrackingStats, SteamGame } from '@shared/types'

interface TrackingState {
  trackedGames: TrackedGame[]
  steamGames: SteamGame[]
  stats: TrackingStats | null
  currentGame: string | null
  isLoading: boolean

  loadTrackedGames: () => Promise<void>
  loadSteamGames: () => Promise<void>
  addGame: (game: Omit<TrackedGame, 'totalTime' | 'lastPlayed'>) => Promise<void>
  removeGame: (gameId: string) => Promise<void>
  updateStats: (stats: TrackingStats) => void
  setCurrentGame: (gameName: string | null) => void
}

export const useTrackingStore = create<TrackingState>((set) => ({
  trackedGames: [],
  steamGames: [],
  stats: null,
  currentGame: null,
  isLoading: false,

  loadTrackedGames: async () => {
    set({ isLoading: true })
    try {
      const games = await window.electronAPI.getTrackedGames()
      set({ trackedGames: games, isLoading: false })
    } catch (error) {
      console.error('Failed to load tracked games:', error)
      set({ isLoading: false })
    }
  },

  loadSteamGames: async () => {
    try {
      const games = await window.electronAPI.getSteamGames()
      set({ steamGames: games })
    } catch (error) {
      console.error('Failed to load Steam games:', error)
    }
  },

  addGame: async (game) => {
    try {
      const newGame = await window.electronAPI.addTrackedGame(game)
      set((state) => ({
        trackedGames: [...state.trackedGames, newGame],
      }))
    } catch (error) {
      console.error('Failed to add game:', error)
      throw error
    }
  },

  removeGame: async (gameId) => {
    try {
      await window.electronAPI.removeTrackedGame(gameId)
      set((state) => ({
        trackedGames: state.trackedGames.filter((g) => g.id !== gameId),
      }))
    } catch (error) {
      console.error('Failed to remove game:', error)
      throw error
    }
  },

  updateStats: (stats) => {
    if (stats.currentGame) {
      console.log('[Tracking] Current game:', stats.currentGame, 'Session:', Math.floor((stats.currentSessionDuration || 0) / 1000), 's')
    }
    set({
      stats,
      currentGame: stats.currentGame || null
    })
  },

  setCurrentGame: (gameName) => set({ currentGame: gameName }),
}))
