import log4js from "log4js";
import { notPrompting } from "../utils.js";
import { startWaiting, stopWaiting } from "../spinner.js";

const logger = log4js.getLogger("IPC");
let mainWindow = null;

export async function setupIPC() {
  // Only import Electron if we're in an Electron environment
  let ipcMain;
  try {
    const electron = await import("electron");
    ipcMain = electron.ipcMain;
    mainWindow = global.mainWindow;
  } catch (error) {
    logger.warn("Electron not available, skipping IPC setup");
    return;
  }

  // Only proceed if we have ipcMain
  if (!ipcMain) {
    logger.warn("ipcMain not available, skipping IPC setup");
    return;
  }

  ipcMain.on("getData", async () => {
    startWaiting("Getting data...", logger);
    try {
      // Get the global socket client instance
      const socketClient = global.socketClient;

      if (!socketClient) {
        sendIPC("setAuthenticated", false);
        sendIPC("setConnected", false);
        sendIPC("setLoading", false);
        sendIPC("setHost", {});
        sendIPC("setPrinters", []);
        sendIPC("setDocumentPrinters", []);
        await stopWaiting();
        return;
      }

      // Send individual data pieces to match renderer expectations
      sendIPC("setAuthenticated", socketClient.authenticated);
      sendIPC("setConnected", socketClient.connected);
      sendIPC("setLoading", socketClient.loading);
      sendIPC("setHost", socketClient.host || {});
      sendIPC("setPrinters", socketClient.printerManager.printers || []);
      sendIPC(
        "setDocumentPrinters",
        socketClient.documentPrinterManager.documentPrinters || [],
      );
      await stopWaiting();
    } catch (error) {
      logger.error("Error getting printer data:", error);
      sendIPC("setAuthenticated", false);
      sendIPC("setConnected", false);
      sendIPC("setLoading", false);
      sendIPC("setHost", {});
      sendIPC("setPrinters", []);
      await stopWaiting();
    }
  });

  // Window management IPC handlers
  ipcMain.on("window-minimize", (event) => {
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.minimize();
    }
  });

  ipcMain.on("window-maximize", (event) => {
    if (mainWindow && !mainWindow.isDestroyed()) {
      if (mainWindow.isMaximized()) {
        mainWindow.unmaximize();
      } else {
        mainWindow.maximize();
      }
    }
  });

  ipcMain.on("window-close", (event) => {
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.close();
    }
  });

  // OTP authentication handler
  ipcMain.on("authenticateOTP", async (event, otp) => {
    startWaiting("Authenticating with OTP...", logger);
    try {
      const socketClient = global.socketClient;
      if (socketClient) {
        notPrompting();
        await socketClient.authenticateWithOtp(otp);
      } else {
        logger.error("Socket client not available for OTP authentication");
      }
      await stopWaiting();
    } catch (error) {
      await stopWaiting();
      logger.error("Error during OTP authentication:", error);
    }
  });

  logger.info("IPC handlers setup complete");
}

export function sendIPC(channel, data) {
  try {
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.webContents.send(channel, data);
      logger.info(`Message sent to main window on channel: ${channel}`, data);
    } else {
      logger.warn(
        `No main window available, cannot send message on channel: ${channel}`
      );
    }
  } catch (error) {
    logger.error(`Error sending message on channel ${channel}:`, error);
  }
}
