import { createContext, useContext, useCallback } from 'react';
import type { ReactNode } from 'react';
import { useJobStatusWebSocket } from '../hooks/useJobStatusWebSocket';
import { useToastContext } from './ToastContext';
import { getStatusMessageConfig } from '../utils/jobStatusMessages';
import type { JobStatusUpdate, ConnectionStatus } from '../hooks/useJobStatusWebSocket';

interface GlobalWebSocketContextType {
  connectionStatus: ConnectionStatus;
  reconnect: () => void;
  disconnect: () => void;
}

const GlobalWebSocketContext = createContext<GlobalWebSocketContextType | undefined>(undefined);

export function GlobalWebSocketProvider({ children }: { children: ReactNode }) {
  const toast = useToastContext();
  
  // Handle job status updates globally
  const handleStatusUpdate = useCallback((update: JobStatusUpdate) => {
    // Use job_title from the update, or fallback to generic message
    const jobTitle = update.job_title || 'Job';
    
    const { message, type, showToast } = getStatusMessageConfig(
      update.status,
      jobTitle,
      update.message
    );
    
    if (showToast) {
      // Pass job_id and job_title to toast for notification integration
      toast[type](message, undefined, update.job_id, update.job_title);
    }
  }, [toast]);

  // Use the existing WebSocket hook for global job list updates (no jobId)
  const { connectionStatus, reconnect, disconnect } = useJobStatusWebSocket(undefined, {
    debug: false,
    autoReconnect: true,
    onStatusUpdate: handleStatusUpdate
  });

  const contextValue: GlobalWebSocketContextType = {
    connectionStatus,
    reconnect,
    disconnect
  };

  return (
    <GlobalWebSocketContext.Provider value={contextValue}>
      {children}
    </GlobalWebSocketContext.Provider>
  );
}

export const useGlobalWebSocket = () => {
  const context = useContext(GlobalWebSocketContext);
  if (context === undefined) {
    throw new Error('useGlobalWebSocket must be used within a GlobalWebSocketProvider');
  }
  return context;
};