'use client';

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { NotificationBar } from './NotificationBar';
import { firebaseMessagingService } from '@/services/firebase-messaging.service';

interface NotificationData {
  id: string;
  title: string;
  body: string;
  timestamp: Date;
  data?: any;
}

interface NotificationContextType {
  showNotification: (notification: Omit<NotificationData, 'id' | 'timestamp'>) => void;
  notifications: NotificationData[];
  clearNotifications: () => void;
}

const NotificationContext = createContext<NotificationContextType | undefined>(undefined);

export const useNotifications = () => {
  const context = useContext(NotificationContext);
  if (!context) {
    throw new Error('useNotifications must be used within a NotificationProvider');
  }
  return context;
};

interface NotificationProviderProps {
  children: ReactNode;
}

export function NotificationProvider({ children }: NotificationProviderProps) {
  const [notifications, setNotifications] = useState<NotificationData[]>([]);
  const [currentNotification, setCurrentNotification] = useState<NotificationData | null>(null);

  useEffect(() => {
    // Initialize Firebase messaging service
    const initializeFirebase = async () => {
      try {
        await firebaseMessagingService.initialize();
      } catch (error) {
        console.error('Error initializing Firebase messaging:', error);
      }
    };

    initializeFirebase();

    // Listen for foreground messages
    const setupForegroundListener = () => {
      if (typeof window !== 'undefined' && 'serviceWorker' in navigator) {
        navigator.serviceWorker.addEventListener('message', (event) => {
          if (event.data && event.data.type === 'PUSH_NOTIFICATION') {
            const notificationData = event.data.payload;
            showNotification({
              title: notificationData.notification?.title || 'New Notification',
              body: notificationData.notification?.body || '',
              data: notificationData.data
            });
          }
        });
      }
    };

    setupForegroundListener();

    // Listen for messages from service worker
    const handleMessage = (event: MessageEvent) => {
      if (event.data && event.data.type === 'FCM_MESSAGE') {
        const payload = event.data.payload;
        showNotification({
          title: payload.notification?.title || 'New Notification',
          body: payload.notification?.body || '',
          data: payload.data
        });
      }
    };

    if (typeof window !== 'undefined') {
      window.addEventListener('message', handleMessage);
    }

    return () => {
      if (typeof window !== 'undefined') {
        window.removeEventListener('message', handleMessage);
      }
    };
  }, []);

  const showNotification = (notification: Omit<NotificationData, 'id' | 'timestamp'>) => {
    const newNotification: NotificationData = {
      ...notification,
      id: Date.now().toString(),
      timestamp: new Date()
    };

    setNotifications(prev => [newNotification, ...prev]);
    setCurrentNotification(newNotification);

    // Auto-hide after 6 seconds
    setTimeout(() => {
      setCurrentNotification(null);
    }, 6000);
  };

  const clearNotifications = () => {
    setNotifications([]);
    setCurrentNotification(null);
  };

  const handleCloseNotification = () => {
    setCurrentNotification(null);
  };

  return (
    <NotificationContext.Provider
      value={{
        showNotification,
        notifications,
        clearNotifications
      }}
    >
      {children}
      <NotificationBar
        notification={currentNotification}
        onClose={handleCloseNotification}
      />
    </NotificationContext.Provider>
  );
}
