import { contextBridge, ipcRenderer } from 'electron';
import type { HostedSessionConfig } from './automation/domain/types/HostedSessionConfig';
import type { AuthenticationState } from './automation/domain/value-objects/AuthenticationState';

export interface AuthStatusEvent {
  state: AuthenticationState;
  message?: string;
  error?: string;
}

export interface AuthCheckResponse {
  success: boolean;
  state?: AuthenticationState;
  error?: string;
}

export interface AuthActionResponse {
  success: boolean;
  message?: string;
  error?: string;
}

export interface CheckoutConfirmationRequest {
  price: string;
  state: 'ready' | 'insufficient_funds';
  sessionMetadata: {
    sessionName: string;
    trackId: string;
    carIds: string[];
  };
  timeoutMs: number;
}

export interface StartAutomationResponse {
  success: boolean;
  sessionId?: string;
  error?: string;
  authRequired?: boolean;
  authState?: AuthenticationState;
}

export interface ElectronAPI {
  startAutomation: (config: HostedSessionConfig) => Promise<StartAutomationResponse>;
  stopAutomation: (sessionId: string) => Promise<{ success: boolean; error?: string }>;
  getSessionStatus: (sessionId: string) => Promise<any>;
  pauseAutomation: (sessionId: string) => Promise<{ success: boolean; error?: string }>;
  resumeAutomation: (sessionId: string) => Promise<{ success: boolean; error?: string }>;
  onSessionProgress: (callback: (progress: any) => void) => void;
  // Authentication APIs
  onAuthStatus: (callback: (status: AuthStatusEvent) => void) => void;
  checkAuth: () => Promise<AuthCheckResponse>;
  initiateLogin: () => Promise<AuthActionResponse>;
  confirmLogin: () => Promise<AuthActionResponse>;
  logout: () => Promise<AuthActionResponse>;
  // Browser Mode APIs
  getBrowserMode: () => Promise<{ mode: 'headed' | 'headless'; isDevelopment: boolean }>;
  setBrowserMode: (mode: 'headed' | 'headless') => Promise<{ success: boolean; mode?: string; error?: string }>;
  // Checkout Confirmation APIs
  onCheckoutConfirmationRequest: (callback: (request: CheckoutConfirmationRequest) => void) => () => void;
  confirmCheckout: (decision: 'confirmed' | 'cancelled' | 'timeout') => void;
  // Overlay / Automation events
  overlayActionRequest: (action: { id: string; label: string; meta?: Record<string, unknown>; timeoutMs?: number }) => Promise<{ id: string; status: 'confirmed' | 'tentative' | 'failed'; reason?: string }>;
  onAutomationEvent: (callback: (event: any) => void) => () => void;
}

contextBridge.exposeInMainWorld('electronAPI', {
  startAutomation: (config: HostedSessionConfig) =>
    ipcRenderer.invoke('start-automation', config) as Promise<StartAutomationResponse>,
  stopAutomation: (sessionId: string) => ipcRenderer.invoke('stop-automation', sessionId),
  getSessionStatus: (sessionId: string) => ipcRenderer.invoke('get-session-status', sessionId),
  pauseAutomation: (sessionId: string) => ipcRenderer.invoke('pause-automation', sessionId),
  resumeAutomation: (sessionId: string) => ipcRenderer.invoke('resume-automation', sessionId),
  onSessionProgress: (callback: (progress: any) => void) => {
    ipcRenderer.on('session-progress', (_event, progress) => callback(progress));
  },
  // Authentication APIs
  onAuthStatus: (callback: (status: AuthStatusEvent) => void) => {
    ipcRenderer.on('auth:status', (_event, status) => callback(status));
  },
  checkAuth: () => ipcRenderer.invoke('auth:check'),
  initiateLogin: () => ipcRenderer.invoke('auth:login'),
  confirmLogin: () => ipcRenderer.invoke('auth:confirmLogin'),
  logout: () => ipcRenderer.invoke('auth:logout'),
  // Browser Mode APIs
  getBrowserMode: () => ipcRenderer.invoke('browser-mode:get'),
  setBrowserMode: (mode: 'headed' | 'headless') => ipcRenderer.invoke('browser-mode:set', mode),
  // Checkout Confirmation APIs
  onCheckoutConfirmationRequest: (callback: (request: CheckoutConfirmationRequest) => void) => {
    const listener = (_event: any, request: CheckoutConfirmationRequest) => callback(request);
    ipcRenderer.on('checkout:request-confirmation', listener);
    return () => {
      ipcRenderer.removeListener('checkout:request-confirmation', listener);
    };
  },
  confirmCheckout: (decision: 'confirmed' | 'cancelled' | 'timeout') => {
    ipcRenderer.send('checkout:confirm', decision);
  },
  // Overlay APIs
  overlayActionRequest: (action: { id: string; label: string; meta?: Record<string, unknown>; timeoutMs?: number }) =>
    ipcRenderer.invoke('overlay-action-request', action),
  onAutomationEvent: (callback: (event: any) => void) => {
    const listener = (_event: any, event: any) => callback(event);
    ipcRenderer.on('automation-event', listener);
    return () => {
      ipcRenderer.removeListener('automation-event', listener);
    };
  },
} as ElectronAPI);