import { app, shell, BrowserWindow, Tray, Menu, nativeImage } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { registerIpcHandlers } from './ipc'
import { cliAliasService } from './services/CliAliasService'

let tray: Tray | null = null
let mainWindow: BrowserWindow | null = null

function createTray(): void {
    const iconPath = process.platform === 'win32'
        ? join(__dirname, '../../resources/icon.ico')
        : join(__dirname, '../../resources/icon.png')
    const icon = nativeImage.createFromPath(iconPath)
    tray = new Tray(icon.isEmpty() ? nativeImage.createEmpty() : icon)

    const contextMenu = Menu.buildFromTemplate([
        { label: 'Trunçgil Multi-PHP', enabled: false },
        { type: 'separator' },
        {
            label: 'Göster/Gizle', click: () => {
                if (mainWindow && !mainWindow.isDestroyed()) {
                    if (mainWindow.isVisible()) mainWindow.hide()
                    else mainWindow.show()
                }
            }
        },
        { type: 'separator' },
        { label: 'Başlat (Tüm Servisler)', click: () => { /* TODO: Start services */ } },
        { label: 'Durdur (Tüm Servisler)', click: () => { /* TODO: Stop services */ } },
        { type: 'separator' },
        {
            label: 'Çıkış', click: () => {
                app.quit()
            }
        }
    ])

    tray.setToolTip('Trunçgil Multi-PHP Server')
    tray.setContextMenu(contextMenu)

    tray.on('double-click', () => {
        if (mainWindow && !mainWindow.isDestroyed()) mainWindow.show()
    })
}

function createWindow(): void {
    mainWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        show: false,
        autoHideMenuBar: true,
        icon: join(__dirname, '../../resources/icon.png'),
        webPreferences: {
            preload: join(__dirname, '../preload/index.js'),
            sandbox: false
        }
    })

    mainWindow.on('ready-to-show', () => {
        if (mainWindow && !mainWindow.isDestroyed()) mainWindow.show()
    })

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

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

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

app.whenReady().then(() => {
    electronApp.setAppUserModelId('com.electron')

    app.on('browser-window-created', (_, window) => {
        optimizer.watchWindowShortcuts(window)
    })

    registerIpcHandlers()
    createWindow()
    createTray()

    // Generate CLI aliases on start
    cliAliasService.generateAliases().catch(console.error)

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

app.on('window-all-closed', () => {
    // Overriding default behavior: stay in tray if all windows closed
    // unless on certain platforms where we really want to quit.
    // For this server app, we often want it to stay alive in Tray.
    if (process.platform === 'darwin') {
        // macOS behavior
    }
})
