import { onMessage } from 'firebase/messaging';
import { createContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { initializeMessaging, getMessagingInstance } from '../config/firebase';
import { redirectByNotificationType } from '../views/Notifications/notificationUtils';

// Create the context
const FirebaseContext = createContext();

const FirebaseProvider = (props) => {
  const [notifications, setNotifications] = useState(null);
  const navigate = useNavigate(); // Initialize navigation without page reload

  useEffect(() => {
    const setupMessaging = async () => {
      const messagingInstance = await initializeMessaging();
      if (messagingInstance) {
        checkNewMessage(messagingInstance);
      }
    };
    
    setupMessaging();
  }, []);

  const showBrowserNotifications = (payload) => {
    // Handle notification click
    const notificationTitle = 'Clinical Notification'; // Customize the title as needed
    const notificationOptions = {
      body: payload.notification.body,
      data: payload.data,
    };
    const notification = new Notification(
      notificationTitle,
      notificationOptions
    );

    notification.onclick = (event) => {
      event.preventDefault(); // Prevent focusing the notification's tab

      // const clickAction =
      //   payload?.data?.baseUrl ||
      //   redirectByNotificationType(
      //     payload.data.type,
      //     payload?.data?.resourceId,
      //     true
      //   ); // Handle notification click
      const clickAction = redirectByNotificationType(
        payload.data.type,
        payload?.data?.resourceId,
        true
      ); // Handle notification click

      // Use navigate to go to the destination without refreshing the page
      if (clickAction) {
        navigate(clickAction, { replace: true });
      }
    };
  };

  const checkNewMessage = (messagingInstance) => {
    if (!messagingInstance) {
      return;
    }

    const handleForegroundNotification = (payload) => {
      setNotifications(() => ({ data: payload?.data || '' }));
      // Display a browser notification
      if (payload.notification) {
        showBrowserNotifications(payload);
      }
    };

    // Listen for messages when the app is in the foreground
    onMessage(messagingInstance, handleForegroundNotification);
  };

  return (
    <FirebaseContext.Provider value={{ notifications, setNotifications }}>
      {props.children}
    </FirebaseContext.Provider>
  );
};

export default FirebaseProvider;

export { FirebaseContext };

