import { useEffect, useState } from "react";
import firebaseApp, { isFirebaseConfigured } from "@/lib/firebase";

export const useFcmToken = () => {
  const [token, setToken] = useState<string | null>(null);
  const [notificationPermissionStatus, setNotificationPermissionStatus] = useState("");

  useEffect(() => {
    if (!isFirebaseConfigured || !firebaseApp) return;

    const retrieveToken = async () => {
      try {
        if (typeof window !== "undefined" && "serviceWorker" in navigator) {
          const { getToken, getMessaging } = await import("firebase/messaging");
          const messaging = getMessaging(firebaseApp);

          const permission = await Notification.requestPermission();
          setNotificationPermissionStatus(permission);

          if (permission === "granted") {
            const currentToken = await getToken(messaging, {
              vapidKey: process.env.NEXT_PUBLIC_VAPID_KEY,
            });
            if (currentToken) {
              setToken(currentToken);
            }
          }
        }
      } catch (error) {
        console.log("An error occurred while retrieving token:", error);
      }
    };

    void retrieveToken();
  }, []);

  return { fcmToken: token, notificationPermissionStatus };
};
