import { useEffect, useState } from "react";
import { MessagePayload, isSupported } from "firebase/messaging";
import { onMessageListener, playNotificationSound } from "./firebase";  // Make sure onMessageListener is imported correctly

const useFCM = (token: string) => {
  const [messages, setMessages] = useState<MessagePayload[]>([]);

  const getNotificationListener = async () => {
    try {
      const supportedBrowser = await isSupported();
      if (supportedBrowser) {
        // Here we are ensuring the onMessageListener is called correctly.
        onMessageListener((message) => {
          playNotificationSound();
          setMessages((prevMessages) => [...prevMessages, message]);  // Adding the new message to state
        });
      }
    } catch (error) {
      console.error("Error checking support:", error);
    }
  };

  useEffect(() => {
    try {
      if (typeof window !== "undefined" && token) {
        getNotificationListener();
      }
    } catch (error) {
      console.error("Error in useEffect:", error);
    }
  }, [token]);

  return { messages, setMessages, getNotificationListener };
};

export default useFCM;
