"use client";

import { useEffect } from "react";
import { setupMessaging } from "@/lib/firebase";
import { getToken, onMessage } from "firebase/messaging";
import { toast } from "sonner";
import { api } from "@/lib/api";
import { ENDPOINTS } from "@/constants/endpoints";

// VAPID key from Firebase Console > Project Settings > Cloud Messaging > Web Push certificates
const VAPID_KEY = process.env.NEXT_PUBLIC_FIREBASE_VAPID_KEY || undefined;

export function NotificationListener() {
  useEffect(() => {
    const initNotifications = async () => {
      try {
        const messaging = await setupMessaging();
        if (!messaging) return;

        // Request permission
        const permission = await Notification.requestPermission();
        if (permission === "granted") {
          const fcmToken = await getToken(messaging, {
            vapidKey: VAPID_KEY,
          });

          if (fcmToken) {
            console.log("FCM Token:", fcmToken);
            // Register this device's FCM token with the backend
            try {
              await api.post(ENDPOINTS.NOTIFICATIONS.REGISTER_TOKEN, { token: fcmToken });
            } catch (err) {
              console.warn("Could not register FCM token:", err);
            }
          } else {
            console.log("No registration token available. Request permission to generate one.");
          }
        } else {
          console.log("Notification permission denied");
        }

        // Listen for foreground messages and show a toast
        const unsubscribe = onMessage(messaging, (payload) => {
          console.log("Foreground message received:", payload);
          toast(payload.notification?.title || "New Notification", {
            description: payload.notification?.body,
            duration: 5000,
          });
        });

        return unsubscribe;
      } catch (error) {
        console.error("Error setting up notifications:", error);
      }
    };

    const unsubscribePromise = initNotifications();

    return () => {
      unsubscribePromise.then((unsubscribe) => {
        if (unsubscribe) unsubscribe();
      });
    };
  }, []);

  return null;
}
