import React, { createContext, useContext, useEffect, useRef, useState, ReactNode } from 'react';
import { useAuthStore } from '../stores/auth.store';
import { useCurrentTenant } from '../stores/tenant.store';
import { showToast } from '../utils/toast';

interface SSEEvent {
  type: string;
  data: any;
  timestamp: string;
}

interface SSEContextType {
  isConnected: boolean;
  lastEvent: SSEEvent | null;
  connect: () => void;
  disconnect: () => void;
  addEventListener: (eventType: string, callback: (data: any) => void) => () => void;
}

const SSEContext = createContext<SSEContextType | undefined>(undefined);

export const useSSE = () => {
  const context = useContext(SSEContext);
  if (context === undefined) {
    throw new Error('useSSE must be used within an SSEProvider');
  }
  return context;
};

interface SSEProviderProps {
  children: ReactNode;
}

export const SSEProvider: React.FC<SSEProviderProps> = ({ children }) => {
  const [isConnected, setIsConnected] = useState(false);
  const [lastEvent, setLastEvent] = useState<SSEEvent | null>(null);
  
  const eventSourceRef = useRef<EventSource | null>(null);
  const eventListenersRef = useRef<Map<string, Set<(data: any) => void>>>(new Map());
  const reconnectTimeoutRef = useRef<NodeJS.Timeout>();
  const reconnectAttempts = useRef(0);
  
  const { isAuthenticated, token } = useAuthStore();
  const currentTenant = useCurrentTenant();

  const connect = () => {
    // Check if we're in demo mode
    const isDemoMode = localStorage.getItem('demo_mode') === 'true';
    const demoSessionId = localStorage.getItem('demo_session_id');

    // For demo mode, we need demo_session_id and tenant
    // For regular mode, we need token and authentication
    if (isDemoMode) {
      if (!demoSessionId || !currentTenant?.id || eventSourceRef.current) {
        console.log('Demo mode: Missing demo session ID or tenant ID for SSE connection');
        return;
      }
    } else {
      if (!isAuthenticated || !token || eventSourceRef.current) {
        console.log('Regular mode: Not authenticated or missing token for SSE connection');
        return;
      }

      // Skip SSE connection for mock tokens in development mode
      if (token === 'mock-jwt-token') {
        console.log('SSE connection skipped for mock token');
        return;
      }
    }

    if (!currentTenant?.id) {
      console.log('No tenant ID available, skipping SSE connection');
      return;
    }

    try {
      // Connect to gateway SSE endpoint with token/demo_session_id and tenant_id
      // Use same protocol and host as the current page to avoid CORS and mixed content issues
      const protocol = window.location.protocol;
      const host = window.location.host;

      let sseUrl: string;
      if (isDemoMode && demoSessionId) {
        // For demo mode, use demo_session_id instead of token
        sseUrl = `${protocol}//${host}/api/events?demo_session_id=${encodeURIComponent(demoSessionId)}&tenant_id=${currentTenant.id}`;
        console.log('Connecting to SSE endpoint (demo mode):', sseUrl);
      } else {
        // For regular mode, use JWT token
        sseUrl = `${protocol}//${host}/api/events?token=${encodeURIComponent(token!)}&tenant_id=${currentTenant.id}`;
        console.log('Connecting to SSE endpoint (regular mode):', sseUrl);
      }

      const eventSource = new EventSource(sseUrl, {
        withCredentials: true,
      });

      eventSource.onopen = () => {
        console.log('SSE connection opened');
        setIsConnected(true);
        reconnectAttempts.current = 0;
        
        if (reconnectTimeoutRef.current) {
          clearTimeout(reconnectTimeoutRef.current);
          reconnectTimeoutRef.current = undefined;
        }
      };

      eventSource.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);

          // Handle different SSE message types from notification service
          if (data.status === 'keepalive') {
            console.log('SSE keepalive received');
            return;
          }

          const sseEvent: SSEEvent = {
            type: data.item_type || 'message',
            data: data,
            timestamp: data.timestamp || new Date().toISOString(),
          };

          setLastEvent(sseEvent);

          // Show notification if it's an alert or recommendation
          if (data.item_type && ['alert', 'recommendation'].includes(data.item_type)) {
            let toastType: 'info' | 'success' | 'warning' | 'error' = 'info';

            if (data.item_type === 'alert') {
              if (data.severity === 'urgent') toastType = 'error';
              else if (data.severity === 'high') toastType = 'error';
              else if (data.severity === 'medium') toastType = 'warning';
              else toastType = 'info';
            } else if (data.item_type === 'recommendation') {
              toastType = 'info';
            }

            showToast[toastType](data.message, { title: data.title || 'Notificación', duration: data.severity === 'urgent' ? 0 : 5000 });
          }

          // Trigger registered listeners
          const listeners = eventListenersRef.current.get(sseEvent.type);
          if (listeners) {
            listeners.forEach(callback => callback(data));
          }

          // Also trigger 'message' listeners for backward compatibility
          const messageListeners = eventListenersRef.current.get('message');
          if (messageListeners) {
            messageListeners.forEach(callback => callback(data));
          }
        } catch (error) {
          console.error('Error parsing SSE message:', error);
        }
      };

      // Handle connection confirmation from gateway
      eventSource.addEventListener('connection', (event) => {
        try {
          const data = JSON.parse(event.data);
          console.log('SSE connection confirmed:', data);
        } catch (error) {
          console.error('Error parsing connection event:', error);
        }
      });

      // Handle heartbeat events (keepalive)
      eventSource.addEventListener('heartbeat', (event) => {
        try {
          const data = JSON.parse(event.data);
          console.log('SSE heartbeat received:', data.timestamp);
        } catch (error) {
          console.error('Error parsing heartbeat event:', error);
        }
      });

      // Handle alert events
      eventSource.addEventListener('alert', (event) => {
        try {
          const data = JSON.parse(event.data);
          const sseEvent: SSEEvent = {
            type: 'alert',
            data,
            timestamp: data.timestamp || new Date().toISOString(),
          };

          setLastEvent(sseEvent);

          // Show alert toast
          let toastType: 'info' | 'success' | 'warning' | 'error' = 'info';
          if (data.severity === 'urgent') toastType = 'error';
          else if (data.severity === 'high') toastType = 'error';
          else if (data.severity === 'medium') toastType = 'warning';
          else toastType = 'info';

          showToast[toastType](data.message, { title: data.title || 'Alerta', duration: data.severity === 'urgent' ? 0 : 5000 });

          // Trigger listeners
          const listeners = eventListenersRef.current.get('alert');
          if (listeners) {
            listeners.forEach(callback => callback(data));
          }
        } catch (error) {
          console.error('Error parsing alert event:', error);
        }
      });

      // Handle recommendation events
      eventSource.addEventListener('recommendation', (event) => {
        try {
          const data = JSON.parse(event.data);
          const sseEvent: SSEEvent = {
            type: 'recommendation',
            data,
            timestamp: data.timestamp || new Date().toISOString(),
          };

          setLastEvent(sseEvent);

          // Show recommendation toast
          showToast.info(data.message, { title: data.title || 'Recomendación', duration: 5000 });

          // Trigger listeners
          const listeners = eventListenersRef.current.get('recommendation');
          if (listeners) {
            listeners.forEach(callback => callback(data));
          }
        } catch (error) {
          console.error('Error parsing recommendation event:', error);
        }
      });

      // Handle inventory_alert events (high/urgent severity alerts from gateway)
      eventSource.addEventListener('inventory_alert', (event) => {
        try {
          const data = JSON.parse(event.data);
          const sseEvent: SSEEvent = {
            type: 'alert',
            data,
            timestamp: data.timestamp || new Date().toISOString(),
          };

          setLastEvent(sseEvent);

          // Show urgent alert toast
          const toastType = data.severity === 'urgent' ? 'error' : 'error';

          showToast[toastType](data.message, { title: data.title || 'Alerta de Inventario', duration: data.severity === 'urgent' ? 0 : 5000 });

          // Trigger alert listeners
          const listeners = eventListenersRef.current.get('alert');
          if (listeners) {
            listeners.forEach(callback => callback(data));
          }
        } catch (error) {
          console.error('Error parsing inventory_alert event:', error);
        }
      });

      // Handle generic notification events from gateway
      eventSource.addEventListener('notification', (event) => {
        try {
          const data = JSON.parse(event.data);
          const sseEvent: SSEEvent = {
            type: data.item_type || 'notification',
            data,
            timestamp: data.timestamp || new Date().toISOString(),
          };

          setLastEvent(sseEvent);

          // Show notification toast
          let toastType: 'info' | 'success' | 'warning' | 'error' = 'info';
          if (data.severity === 'urgent') toastType = 'error';
          else if (data.severity === 'high') toastType = 'warning';
          else if (data.severity === 'medium') toastType = 'info';

          showToast[toastType](data.message, { title: data.title || 'Notificación', duration: data.severity === 'urgent' ? 0 : 5000 });

          // Trigger listeners for both notification and specific type
          const notificationListeners = eventListenersRef.current.get('notification');
          if (notificationListeners) {
            notificationListeners.forEach(callback => callback(data));
          }

          if (data.item_type) {
            const typeListeners = eventListenersRef.current.get(data.item_type);
            if (typeListeners) {
              typeListeners.forEach(callback => callback(data));
            }
          }
        } catch (error) {
          console.error('Error parsing notification event:', error);
        }
      });

      eventSource.onerror = (error) => {
        console.error('SSE connection error:', error);
        setIsConnected(false);
        
        if (eventSource.readyState === EventSource.CLOSED) {
          // Attempt reconnection with exponential backoff
          const delay = Math.min(1000 * Math.pow(2, reconnectAttempts.current), 30000);
          reconnectAttempts.current++;
          
          reconnectTimeoutRef.current = setTimeout(() => {
            if (isAuthenticated && token) {
              connect();
            }
          }, delay);
        }
      };


      eventSourceRef.current = eventSource;
    } catch (error) {
      console.error('Failed to establish SSE connection:', error);
      setIsConnected(false);
    }
  };

  const disconnect = () => {
    if (eventSourceRef.current) {
      eventSourceRef.current.close();
      eventSourceRef.current = null;
    }
    
    if (reconnectTimeoutRef.current) {
      clearTimeout(reconnectTimeoutRef.current);
      reconnectTimeoutRef.current = undefined;
    }
    
    setIsConnected(false);
    reconnectAttempts.current = 0;
  };

  const addEventListener = (eventType: string, callback: (data: any) => void) => {
    if (!eventListenersRef.current.has(eventType)) {
      eventListenersRef.current.set(eventType, new Set());
    }
    
    eventListenersRef.current.get(eventType)!.add(callback);
    
    // Return cleanup function
    return () => {
      const listeners = eventListenersRef.current.get(eventType);
      if (listeners) {
        listeners.delete(callback);
        if (listeners.size === 0) {
          eventListenersRef.current.delete(eventType);
        }
      }
    };
  };

  // Connect when authenticated, disconnect when not or when tenant changes
  useEffect(() => {
    const isDemoMode = localStorage.getItem('demo_mode') === 'true';
    const demoSessionId = localStorage.getItem('demo_session_id');

    // For demo mode: connect if we have demo_session_id and tenant
    // For regular mode: connect if authenticated with token and tenant
    const shouldConnect = isDemoMode
      ? (demoSessionId && currentTenant)
      : (isAuthenticated && token && currentTenant);

    if (shouldConnect) {
      connect();
    } else {
      disconnect();
    }

    return () => {
      disconnect();
    };
  }, [isAuthenticated, token, currentTenant?.id]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      disconnect();
    };
  }, []);

  const contextValue: SSEContextType = {
    isConnected,
    lastEvent,
    connect,
    disconnect,
    addEventListener,
  };

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