import { app, dialog } from 'electron'
import * as fs from 'node:fs'
import * as path from 'node:path'

import { getGamePath } from 'steam-game-path'

import { mainWindow } from '../index'

export interface Settings {
  SkyrimPath: string
  lang: 'en' | 'ru' | 'uk'
  autoUpdate: boolean
  startOnBoot: boolean
  currentServer: string
}

const defaultSettings: Settings = {
  autoUpdate: true,
  startOnBoot: true,
  lang: 'en',
  SkyrimPath: '',
  currentServer: ''
}

const settingsFilePath = path.join(app.getPath('userData'), 'settings.json')

export function loadSettings(): Settings {
  try {
    if (!fs.existsSync(settingsFilePath)) {
      fs.writeFileSync(settingsFilePath, JSON.stringify(defaultSettings, null, 2))
      return defaultSettings
    }

    const data = fs.readFileSync(settingsFilePath, 'utf-8')
    return JSON.parse(data) as Settings
  } catch (error) {
    console.error('Error loading settings:', error)
    return defaultSettings
  }
}

export function saveSettings(newSettings: Settings): void {
  try {
    fs.writeFileSync(settingsFilePath, JSON.stringify(newSettings, null, 2))
  } catch (error) {
    console.error('Error saving settings:', error)
  }
}

function showSkyrimSelectorDialog(): string[] | undefined {
  return dialog.showOpenDialogSync(mainWindow, {
    properties: ['openFile'],
    filters: [{ name: 'SkyrimSE.exe', extensions: ['exe'] }]
  })
}

function skyrimSelectorDialog(): boolean {
  const filePaths = showSkyrimSelectorDialog()

  if (!filePaths || filePaths.length === 0) {
    const settings = loadSettings()
    settings.SkyrimPath = ''
    saveSettings(settings)
    return false
  }

  const selectedFile = filePaths[0]

  if (path.basename(selectedFile).toLowerCase() !== 'skyrimse.exe') {
    dialog.showErrorBox('Invalid file', 'Please select SkyrimSE.exe')
    skyrimSelectorDialog()
    return false
  }

  const settings = loadSettings()
  settings.SkyrimPath = path.dirname(selectedFile)
  saveSettings(settings)

  return true
}

export function verifySkyrimInstallation(): void {
  const localSettings = loadSettings()
  if (localSettings.SkyrimPath.length !== 0) return

  const foundedSSEPath = getGamePath(489830, true)

  if (foundedSSEPath && foundedSSEPath.game) {
    localSettings.SkyrimPath = foundedSSEPath.game.path
    saveSettings(localSettings)
    return
  }

  const result = skyrimSelectorDialog()
  console.log(`Status of Skyrim selection: ${result}`)
}
