import type { TrackedGame, TrackingStats, GameSession } from '../../shared/types'
import type { StoreType, GameTrackingData } from '../storeTypes'

export type { GameTrackingData }

export function getTrackedGames(store: StoreType): TrackedGame[] {
  const trackedGames = store.get('trackedGames') || {}
  return Object.values(trackedGames)
}

export function addTrackedGame(
  store: StoreType,
  game: Omit<TrackedGame, 'totalTime' | 'lastPlayed'>
): TrackedGame {
  const trackedGames = store.get('trackedGames') || {}

  const newGame: TrackedGame = {
    ...game,
    totalTime: 0,
    lastPlayed: undefined,
  }

  trackedGames[game.id] = newGame
  store.set('trackedGames', trackedGames)

  // Initialize tracking data
  const trackingData = store.get('trackingData') || {}
  trackingData[game.id] = {
    totalTime: 0,
    sessions: [],
    lastPlayed: 0,
  }
  store.set('trackingData', trackingData)

  return newGame
}

export function removeTrackedGame(store: StoreType, gameId: string): void {
  const trackedGames = store.get('trackedGames') || {}
  delete trackedGames[gameId]
  store.set('trackedGames', trackedGames)

  const trackingData = store.get('trackingData') || {}
  delete trackingData[gameId]
  store.set('trackingData', trackingData)
}

export function updateGameTime(store: StoreType, gameId: string, duration: number): void {
  // Update tracked games
  const trackedGames = store.get('trackedGames') || {}
  if (trackedGames[gameId]) {
    trackedGames[gameId].totalTime += duration
    trackedGames[gameId].lastPlayed = Date.now()
    store.set('trackedGames', trackedGames)
  }

  // Update tracking data with session
  const trackingData = store.get('trackingData') || {}
  if (!trackingData[gameId]) {
    trackingData[gameId] = {
      totalTime: 0,
      sessions: [],
      lastPlayed: 0,
    }
  }

  const now = Date.now()
  trackingData[gameId].totalTime += duration
  trackingData[gameId].lastPlayed = now
  trackingData[gameId].sessions.push({
    startTime: now - duration,
    endTime: now,
    duration,
  })

  // Keep only last 100 sessions to prevent data bloat
  if (trackingData[gameId].sessions.length > 100) {
    trackingData[gameId].sessions = trackingData[gameId].sessions.slice(-100)
  }

  store.set('trackingData', trackingData)
}

export function getTrackingStats(store: StoreType): TrackingStats {
  const trackingData = store.get('trackingData') || {}
  const now = Date.now()

  const todayStart = new Date().setHours(0, 0, 0, 0)
  const weekStart = now - 7 * 24 * 60 * 60 * 1000
  const monthStart = now - 30 * 24 * 60 * 60 * 1000

  let totalTimeToday = 0
  let totalTimeWeek = 0
  let totalTimeMonth = 0
  const recentSessions: GameSession[] = []

  for (const [gameId, data] of Object.entries(trackingData)) {
    for (const session of data.sessions) {
      if (session.endTime >= monthStart) {
        totalTimeMonth += session.duration

        if (session.endTime >= weekStart) {
          totalTimeWeek += session.duration
        }

        if (session.endTime >= todayStart) {
          totalTimeToday += session.duration
        }
      }
    }

    // Get last session for each game
    if (data.sessions.length > 0) {
      const lastSession = data.sessions[data.sessions.length - 1]
      const trackedGames = store.get('trackedGames') || {}
      const game = trackedGames[gameId]

      if (game && lastSession.endTime >= weekStart) {
        recentSessions.push({
          gameId,
          gameName: game.name,
          startTime: lastSession.startTime,
          endTime: lastSession.endTime,
          duration: lastSession.duration,
          isActive: false,
        })
      }
    }
  }

  // Sort by most recent
  recentSessions.sort((a, b) => (b.endTime || 0) - (a.endTime || 0))

  return {
    totalTimeToday,
    totalTimeWeek,
    totalTimeMonth,
    sessions: recentSessions.slice(0, 10),
  }
}

export function formatTime(ms: number): string {
  const seconds = Math.floor(ms / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)

  if (hours > 0) {
    const remainingMinutes = minutes % 60
    return `${hours}ч ${remainingMinutes}м`
  } else if (minutes > 0) {
    return `${minutes}м`
  } else {
    return `${seconds}с`
  }
}
