import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
const { loginUser, forgotPassword } = require('../../database/Models/Users')

let splashWindow
let mainWindow

// Create splash window
function createSplashScreen() {
  splashWindow = new BrowserWindow({
    width: 400,
    height: 300,
    frame: false,
    alwaysOnTop: true,
    transparent: true,
    resizable: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })

  splashWindow.loadFile(join(__dirname, '../renderer/splash.html'))

  splashWindow.on('closed', () => {
    splashWindow = null
  })
}

// Create main application window
function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1000,
    minWidth: 1000,
    height: 670,
    minHeight: 670,
    show: false,
    autoHideMenuBar: true,
    fullscreen: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      nodeIntegration: true,
      contextIsolation: true,
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    if (splashWindow) {
      splashWindow.close() // Close splash screen when main window is ready
    }
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // Load the initial content
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// Function to load new content and show the splash screen
function loadNewContent(contentPath) {
  createSplashScreen() // Show splash screen before loading new content

  mainWindow.loadFile(contentPath).then(() => {
    if (splashWindow) {
      splashWindow.close() // Close splash screen after loading content
    }
    mainWindow.show() // Show main window
  })
}

// This method will be called when Electron has finished initialization
app.whenReady().then(() => {
  // Set app user model id for Windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // Create initial main window
  createWindow()

  // IPC for loading new content
  ipcMain.on('load-content', (event, contentPath) => {
    loadNewContent(contentPath)
  })

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// Event for handling login
ipcMain.handle('login', async (event, credentials) => {
  const { username, password } = credentials

  const users = await loginUser(username, password)

  if (users) {
    return { success: true, user: users }
  } else {
    return { success: false }
  }
})

// Event for handling forgot password
ipcMain.handle('forgotPassword', async (event, credentials) => {
  const { email, password, passwordConfirmation } = credentials

  const updated = await forgotPassword(email, password, passwordConfirmation)

  if (updated) {
    return updated
  }
})
