"use client";

import { useEffect, useRef } from "react";
import { onForegroundMessage } from "@/utils/firebase";
import axios from "@/utils/axios-config";
import { getToken } from "@/utils/cookie-config";
import { useDispatch } from "react-redux";
import { fetchNotificationLength } from "@/store/notification/actions";

export default function FCMProvider() {
  const initialized = useRef(false);
  const dispatch = useDispatch();

  // Fetch the real notification count from the API
  const refreshNotificationCount = async () => {
    try {
      const authToken = getToken();
      if (!authToken) return;

      const response = await axios.get("/notifications");
      const count = response?.headers["x-unreadnotification-count"];
      dispatch(fetchNotificationLength(Number(count) || 0));
    } catch (error) {
      console.error("Failed to fetch notification count:", error);
    }
  };

  useEffect(() => {
    if (initialized.current) return;
    initialized.current = true;

    // Register the service worker (needed for receiving push messages)
    if ("serviceWorker" in navigator) {
      navigator.serviceWorker.register("/firebase-messaging-sw.js").catch((error) => {
        console.error("Service worker registration failed:", error);
      });
    }

    // Listen for foreground messages
    onForegroundMessage((payload) => {
      console.log("Foreground message received:", payload);

      // Support both notification messages and data-only messages
      const title = payload.notification?.title || payload.data?.title || "New Notification";
      const body = payload.notification?.body || payload.data?.body || "";

      // Show a browser notification even when the app is focused
      if (Notification.permission === "granted") {
        new Notification(title, {
          body: body,
          icon: "/icon.svg",
        });
      }

      // Fetch the real count from the API
      refreshNotificationCount();
    });

    // Listen for messages from the service worker (background notifications)
    const handleServiceWorkerMessage = (event: MessageEvent) => {
      if (event.data?.type === "NEW_NOTIFICATION") {
        console.log("Background notification received via service worker:", event.data.payload);
        refreshNotificationCount();
      }
    };
    navigator.serviceWorker?.addEventListener("message", handleServiceWorkerMessage);

    return () => {
      navigator.serviceWorker?.removeEventListener("message", handleServiceWorkerMessage);
    };
  }, [dispatch]);

  return null;
}
