import { autoUpdater } from 'electron-updater'
import { BrowserWindow, ipcMain, app } from 'electron'
import * as path from 'path'

let splashWindow: BrowserWindow | null = null

export function createSplashWindow(): BrowserWindow {
  splashWindow = new BrowserWindow({
    width: 350,
    height: 250,
    frame: false,
    transparent: false,
    resizable: false,
    center: true,
    backgroundColor: '#0d0e14',
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  })

  const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged

  if (isDev) {
    // In dev mode: __dirname is dist/main/main/, need to go up 3 levels to project root
    splashWindow.loadFile(path.join(__dirname, '../../../src/renderer/splash.html'))
  } else {
    // In production: __dirname is dist/main/main/, so go up twice to dist/renderer/
    splashWindow.loadFile(path.join(__dirname, '../../renderer/splash.html'))
  }

  return splashWindow
}

export function closeSplashWindow() {
  if (splashWindow) {
    splashWindow.close()
    splashWindow = null
  }
}

function sendStatusToSplash(status: string) {
  if (splashWindow) {
    splashWindow.webContents.send('update-status', status)
  }
}

function sendProgressToSplash(percent: number) {
  if (splashWindow) {
    splashWindow.webContents.send('update-progress', percent)
  }
}

export function setupAutoUpdater(onComplete: () => void) {
  const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged

  // In development, skip update check
  if (isDev) {
    console.log('[Updater] Skipping update check in development mode')
    sendStatusToSplash('Режим разработки')
    setTimeout(() => {
      closeSplashWindow()
      onComplete()
    }, 1500)
    return
  }

  // Configure auto-updater
  autoUpdater.autoDownload = true
  autoUpdater.autoInstallOnAppQuit = true

  // Check for updates
  autoUpdater.on('checking-for-update', () => {
    console.log('[Updater] Checking for updates...')
    sendStatusToSplash('Проверка обновлений...')
  })

  autoUpdater.on('update-available', (info) => {
    console.log('[Updater] Update available:', info.version)
    sendStatusToSplash(`Найдено обновление v${info.version}`)
  })

  autoUpdater.on('update-not-available', () => {
    console.log('[Updater] No updates available')
    sendStatusToSplash('Актуальная версия')
    setTimeout(() => {
      closeSplashWindow()
      onComplete()
    }, 1000)
  })

  autoUpdater.on('download-progress', (progress) => {
    const percent = Math.round(progress.percent)
    console.log(`[Updater] Download progress: ${percent}%`)
    sendStatusToSplash(`Загрузка обновления... ${percent}%`)
    sendProgressToSplash(percent)
  })

  autoUpdater.on('update-downloaded', (info) => {
    console.log('[Updater] Update downloaded:', info.version)
    sendStatusToSplash('Установка обновления...')
    // Install and restart
    setTimeout(() => {
      autoUpdater.quitAndInstall(false, true)
    }, 1500)
  })

  autoUpdater.on('error', (error) => {
    console.error('[Updater] Error:', error)
    sendStatusToSplash('Ошибка проверки обновлений')
    setTimeout(() => {
      closeSplashWindow()
      onComplete()
    }, 2000)
  })

  // Start checking
  autoUpdater.checkForUpdates().catch((error) => {
    console.error('[Updater] Failed to check for updates:', error)
    sendStatusToSplash('Не удалось проверить обновления')
    setTimeout(() => {
      closeSplashWindow()
      onComplete()
    }, 2000)
  })
}

// Manual check for updates (from settings)
export function checkForUpdatesManual(): Promise<{ available: boolean; version?: string; error?: string }> {
  return new Promise((resolve) => {
    const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged

    if (isDev) {
      resolve({ available: false, error: 'В режиме разработки обновления недоступны' })
      return
    }

    const onUpdateAvailable = (info: { version: string }) => {
      cleanup()
      resolve({ available: true, version: info.version })
    }

    const onUpdateNotAvailable = () => {
      cleanup()
      resolve({ available: false })
    }

    const onError = (error: Error) => {
      cleanup()
      resolve({ available: false, error: error.message })
    }

    const cleanup = () => {
      autoUpdater.off('update-available', onUpdateAvailable)
      autoUpdater.off('update-not-available', onUpdateNotAvailable)
      autoUpdater.off('error', onError)
    }

    autoUpdater.on('update-available', onUpdateAvailable)
    autoUpdater.on('update-not-available', onUpdateNotAvailable)
    autoUpdater.on('error', onError)

    autoUpdater.checkForUpdates().catch((error) => {
      cleanup()
      resolve({ available: false, error: error.message })
    })
  })
}

// Setup IPC handlers for updates
export function setupUpdateIpcHandlers() {
  ipcMain.handle('get-app-version', () => {
    return app.getVersion()
  })

  ipcMain.handle('check-for-updates', async () => {
    return await checkForUpdatesManual()
  })

  ipcMain.handle('download-update', () => {
    autoUpdater.downloadUpdate()
  })

  ipcMain.handle('install-update', () => {
    autoUpdater.quitAndInstall(false, true)
  })
}
