import { ipcMain, BrowserWindow } from 'electron'
import { setupAutoLaunch } from './autolaunch'
import { getRunningProcesses, getForegroundWindow } from './tracking/processTracker'
import { getSteamGames, getSteamPath } from './tracking/steamIntegration'
import { getTrackingStats, getTrackedGames, addTrackedGame, removeTrackedGame } from './tracking/timeStorage'
import { ApiClient } from './apiClient'
import type { TrackedGame, AppSettings, User, LoginResponse } from '../shared/types'
import type { StoreType } from './storeTypes'

export function setupIpcHandlers(
  store: StoreType,
  getMainWindow: () => BrowserWindow | null
) {
  const apiClient = new ApiClient(store)
  // Settings handlers
  ipcMain.handle('get-settings', () => {
    return store.get('settings')
  })

  ipcMain.handle('save-settings', async (_event, settings: Partial<AppSettings>) => {
    const currentSettings = store.get('settings')
    const newSettings = { ...currentSettings, ...settings }
    store.set('settings', newSettings)

    // Handle auto-launch setting change
    if (settings.autoLaunch !== undefined) {
      await setupAutoLaunch(settings.autoLaunch)
    }

    return newSettings
  })

  // Auth handlers
  ipcMain.handle('get-token', () => {
    return store.get('token')
  })

  ipcMain.handle('save-token', (_event, token: string) => {
    store.set('token', token)
  })

  ipcMain.handle('clear-token', () => {
    store.set('token', null)
  })

  // Process tracking handlers
  ipcMain.handle('get-running-processes', async () => {
    return await getRunningProcesses()
  })

  ipcMain.handle('get-foreground-window', async () => {
    return await getForegroundWindow()
  })

  ipcMain.handle('get-tracking-stats', () => {
    return getTrackingStats(store)
  })

  // Steam handlers
  ipcMain.handle('get-steam-games', async () => {
    return await getSteamGames()
  })

  ipcMain.handle('get-steam-path', () => {
    return getSteamPath()
  })

  // Tracked games handlers
  ipcMain.handle('get-tracked-games', () => {
    return getTrackedGames(store)
  })

  ipcMain.handle('add-tracked-game', (_event, game: Omit<TrackedGame, 'totalTime' | 'lastPlayed'>) => {
    return addTrackedGame(store, game)
  })

  ipcMain.handle('remove-tracked-game', (_event, gameId: string) => {
    removeTrackedGame(store, gameId)
  })

  // API handlers - all requests go through main process (no CORS issues)
  ipcMain.handle('api-login', async (_event, login: string, password: string) => {
    console.log('[API] Login attempt for:', login)
    try {
      const response = await apiClient.post<LoginResponse>('/auth/login', { login, password })
      console.log('[API] Login response:', response.status)

      // Save token if login successful
      if (response.data.access_token) {
        store.set('token', response.data.access_token)
      }

      return { success: true, data: response.data }
    } catch (error: unknown) {
      console.error('[API] Login error:', error)
      const err = error as { status?: number; message?: string; detail?: unknown }
      return {
        success: false,
        error: err.detail || err.message || 'Login failed',
        status: err.status
      }
    }
  })

  ipcMain.handle('api-get-me', async () => {
    try {
      const response = await apiClient.get<User>('/auth/me')
      return { success: true, data: response.data }
    } catch (error: unknown) {
      const err = error as { status?: number; message?: string; detail?: unknown }
      return {
        success: false,
        error: err.detail || err.message || 'Failed to get user',
        status: err.status
      }
    }
  })

  ipcMain.handle('api-2fa-verify', async (_event, sessionId: number, code: string) => {
    console.log('[API] 2FA verify attempt')
    try {
      const response = await apiClient.post<LoginResponse>(`/auth/2fa/verify?session_id=${sessionId}&code=${code}`)
      console.log('[API] 2FA verify response:', response.status)

      // Save token if verification successful
      if (response.data.access_token) {
        store.set('token', response.data.access_token)
      }

      return { success: true, data: response.data }
    } catch (error: unknown) {
      console.error('[API] 2FA verify error:', error)
      const err = error as { status?: number; message?: string; detail?: unknown }
      return {
        success: false,
        error: err.detail || err.message || '2FA verification failed',
        status: err.status
      }
    }
  })

  ipcMain.handle('api-request', async (_event, method: string, endpoint: string, data?: unknown) => {
    try {
      let response
      switch (method.toUpperCase()) {
        case 'GET':
          response = await apiClient.get(endpoint)
          break
        case 'POST':
          response = await apiClient.post(endpoint, data)
          break
        case 'PUT':
          response = await apiClient.put(endpoint, data)
          break
        case 'PATCH':
          response = await apiClient.patch(endpoint, data)
          break
        case 'DELETE':
          response = await apiClient.delete(endpoint)
          break
        default:
          throw new Error(`Unknown method: ${method}`)
      }
      return { success: true, data: response.data }
    } catch (error: unknown) {
      const err = error as { status?: number; message?: string; detail?: unknown }
      return {
        success: false,
        error: err.detail || err.message || 'Request failed',
        status: err.status
      }
    }
  })
}
