import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { BrowserWindow, GlobalShortcut } from 'electrobun/bun'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const DEV_SERVER_PORT = 5780
const DEV_SERVER_URL = `http://localhost:${DEV_SERVER_PORT}`
const SPOTLIGHT_ROUTE_PATH = '/dashboard/electron/spotlightcontent'

let spotlightWindow = null

function getSpotlightRouteUrl() {
  if (process.env.NODE_ENV === 'development') {
    return `${DEV_SERVER_URL}${SPOTLIGHT_ROUTE_PATH}`
  }

  return `views://mainview/index.html#${SPOTLIGHT_ROUTE_PATH}`
}

export function openSpotlightContentWindow(rpc) {
  if (spotlightWindow && !spotlightWindow.isDestroyed?.()) {
    spotlightWindow.show?.()
    spotlightWindow.focus?.()
    return spotlightWindow
  }

  spotlightWindow = new BrowserWindow({
    title: 'Farm Control Spotlight',
    url: getSpotlightRouteUrl(),
    rpc,
    transparent: true,
    frame: {
      width: 700,
      height: 40,
      x: 100,
      y: 100
    }
  })

  spotlightWindow.on?.('close', (event) => {
    event?.preventDefault?.()
    if (spotlightWindow && !spotlightWindow.isDestroyed?.()) {
      spotlightWindow.hide?.()
    }
  })

  spotlightWindow.on?.('blur', () => {
    if (spotlightWindow && !spotlightWindow.isDestroyed?.()) {
      spotlightWindow.hide?.()
    }
  })

  return spotlightWindow
}

export function getSpotlightWindow() {
  return spotlightWindow
}

export function registerGlobalShortcuts(rpc) {
  try {
    const registered = GlobalShortcut.register('Alt+Shift+Q', () => {
      openSpotlightContentWindow(rpc)
    })

    if (!registered) {
      console.warn('[globalShortcut] Failed to register Alt+Shift+Q')
    }
  } catch (error) {
    console.warn(
      '[globalShortcut] Error registering Alt+Shift+Q',
      error?.message || error
    )
  }
}

export function unregisterGlobalShortcuts() {
  try {
    GlobalShortcut.unregisterAll()
  } catch (error) {
    console.warn(
      '[globalShortcut] Error unregistering shortcuts',
      error?.message || error
    )
  }
}

export function resizeSpotlightWindow(height) {
  if (!spotlightWindow || spotlightWindow.isDestroyed?.()) return false

  try {
    const frame = spotlightWindow.getFrame?.() || spotlightWindow.getBounds?.()
    const width = frame?.width || 700
    spotlightWindow.setSize?.(width, height)
    spotlightWindow.center?.()
    return true
  } catch (error) {
    console.warn(
      '[spotlight] Failed to resize window.',
      error?.message || error
    )
    return false
  }
}
