import { app, BrowserWindow, ipcMain } from 'electron';
import * as path from 'path';
import { NetworkClient } from './network-client';

let mainWindow: BrowserWindow | null = null;
let networkClient: NetworkClient | null = null;

function createWindow(): void {
  mainWindow = new BrowserWindow({
    width: 1024,
    height: 720,
    minWidth: 800,
    minHeight: 600,
    title: 'Network Tool - 异地组网客户端',
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  // 开发模式加载 Vite dev server
  const isDev = !app.isPackaged;
  if (isDev) {
    mainWindow.loadURL('http://localhost:5173');
    mainWindow.webContents.openDevTools({ mode: 'detach' });
  } else {
    mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'));
  }

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

// 初始化网络客户端
function initNetworkClient(): void {
  networkClient = new NetworkClient();
}

// IPC 处理器
function setupIPC(): void {
  // 用户相关
  ipcMain.handle('auth:register', async (_event, email: string, password: string) => {
    try {
      const result = await networkClient!.apiRequest('/api/auth/register', 'POST', { email, password });
      return result;
    } catch (err: any) {
      return { success: false, error: 'NETWORK_ERROR', message: err.message };
    }
  });

  ipcMain.handle('auth:login', async (_event, email: string, password: string) => {
    try {
      const result = await networkClient!.apiRequest('/api/auth/login', 'POST', { email, password });
      if (result.success) {
        networkClient!.setToken(result.data.token);
      }
      return result;
    } catch (err: any) {
      return { success: false, error: 'NETWORK_ERROR', message: err.message };
    }
  });

  ipcMain.handle('auth:me', async () => {
    return networkClient!.authenticatedRequest('/api/auth/me');
  });

  // 设备相关
  ipcMain.handle('device:register', async (_event, data: any) => {
    return networkClient!.authenticatedRequest('/api/devices/register', 'POST', data);
  });

  ipcMain.handle('device:list', async () => {
    return networkClient!.authenticatedRequest('/api/devices');
  });

  ipcMain.handle('device:updateStatus', async (_event, id: number, status: string) => {
    return networkClient!.authenticatedRequest(`/api/devices/${id}/status`, 'PATCH', { status });
  });

  ipcMain.handle('device:delete', async (_event, id: number) => {
    return networkClient!.authenticatedRequest(`/api/devices/${id}`, 'DELETE');
  });

  // 节点相关
  ipcMain.handle('node:list', async () => {
    return networkClient!.authenticatedRequest('/api/nodes');
  });

  ipcMain.handle('node:available', async () => {
    return networkClient!.authenticatedRequest('/api/nodes/available');
  });

  // 连接相关
  ipcMain.handle('connection:request', async (_event, data: any) => {
    return networkClient!.authenticatedRequest('/api/connections/request', 'POST', data);
  });

  ipcMain.handle('connection:disconnect', async (_event, deviceId: number) => {
    return networkClient!.authenticatedRequest('/api/connections/disconnect', 'POST', { device_id: deviceId });
  });

  ipcMain.handle('connection:logs', async () => {
    return networkClient!.authenticatedRequest('/api/connections/logs');
  });

  // Relay Node TCP 连接
  ipcMain.handle('relay:connect', async (_event, host: string, port: number, token: string, deviceId: number) => {
    try {
      await networkClient!.connectToRelay(host, port, token, deviceId);
      return { success: true };
    } catch (err: any) {
      return { success: false, error: 'RELAY_CONNECT_FAILED', message: err.message };
    }
  });

  ipcMain.handle('relay:send', async (_event, targetDeviceId: number, payload: string) => {
    try {
      networkClient!.sendMessage(targetDeviceId, payload);
      return { success: true };
    } catch (err: any) {
      return { success: false, error: 'SEND_FAILED', message: err.message };
    }
  });

  ipcMain.handle('relay:disconnect', async () => {
    networkClient!.disconnectFromRelay();
    return { success: true };
  });

  // Relay 事件 → 渲染进程
  networkClient?.on('message', (msg: any) => {
    mainWindow?.webContents.send('relay:message', msg);
  });

  networkClient?.on('status', (status: string) => {
    mainWindow?.webContents.send('relay:status', status);
  });
}

// 应用生命周期
app.whenReady().then(() => {
  initNetworkClient();
  setupIPC();
  createWindow();

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

app.on('window-all-closed', () => {
  networkClient?.disconnectFromRelay();
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
